*updated 9/13/2023 for paper refresh

cd "$output"
program drop _all

*graphing preferences
graph set window fontface default
graph set eps fontface default
set scheme plotplainblind, perm

global color_1   gs10 	
global color_2   gs5
global color_3 	 black
global color_4   gs12

global color_b   gs10	 
global color_a   black

global color_c   gs10  
global color_t    black 

*  ananas sky turquoise reddish vermillion  orangebrown 

* clustering,  

****************SWITCHES*********************
global programs_globals 		1 //always leave on -- set up utilities for processing the data

global fn_cps 					1 // voting trends from CPS by ed
global tn_voter_pred			1 //voting outcomes based on predicted voting using BPS covariates 

*lottery details
global tn_covbal				1 //covariate balance on the lottery
global tn_means					1 //BPS, charter, winner/loser menas
global tn_lottorecords			1 //lottery details for appendix
global tn_simsmatch				1 //match rate to sims by lottery 
global tn_attrition				1 //attrition in the lottery sample
global tn_first_stage			1 //first stage

*main impacts
global tn_attend_susp			1 // charter impacts on high school attendance and suspension
global tn_academic				1 // charter impacts on MCAS, SAT, AP, progression through HS, HS grad, college enrollment
global fn_academic				1 // charter impacts on MCAS, SAT, AP, progression through HS, HS grad, college enrollment Figure
global tn_instate_outstate 		1 // charter impacts on in-state vs out-of-state college
global tn_voter					1 // charter impacts on voting including ITT
global fn_voter					1 // main charter impacts on voting as figure
global fn_voter_overtime		1 // charter impacts over time
global fn_combined				1 // cobmine voting graphs
global f_baseline_peers			1 // plot impact on baseline peers

*voter details and robustness
global tn_voter_close			1 // voting impacts split by time near election
global tn_voter_detailed		1 // charter voting impacts on subsamples (in-state/out-of-state college)
global tn_voter_imputed			1 // charter voting impacts with imputations for out of state college goers
global tn_ltospec				1 // why are impacts different from Angrist et al 2006? 
global fn_robust				1 // omiting schools and cohorts (graphs)
global tn_robust				1 // alternative specifications
global tn_students_voterfile	1 // percent of students that appear in voter files

*mechanisms
global tn_community				1 // charter impacts on community voting via college MUST BE RUN BEFORE tn_extra
global fn_mission				1 // impacts by mission statement figure
global tn_mission				1 // impacts by mission statement
global tn_voter_sub				1 // voting impacts on subgroups
global fn_voter_sub				1 // voting impacts on subgroups figure
global f_cog_noncog				1 // exploration of cognitive/noncog channel


if $programs_globals==1{
*DEFINE GLOBALS
	global covariates baselinefemale baselineblack baselinehisp baselineasian baselineotherrace ///
		baselinesped baselinelep baselinefrpl  yobdum* yeardum*
	global baselinetests baseline_e baseline_m

	global longvote ever_registered registered_by_19  ever_voted ever_general ever_pres ever_gen_offcycle  ever_pprimary   first_pos_pres  second_pos_pres
	
	global shortvote ever_registered share_pres first_pos_pres

*risk sets
global risksets db_*

*cluster variable
global clustervar schoolXyear
***** Options for table formating *****
global opts	a f plain coll(none) nodep nomti c(b(star  fmt(%9.3f)) se(abs par fmt(%9.3f))) star( * .10 ** .05 *** .01 ) noobs
*******Standard table notes***************
global note_rf		"Each coefficient labeled Initial Offer or Waitlist Offer is the reduced form estimate of an offer of seat at a Boston charter on the outcome listed in the row heading. "
global note_iv		"Each coefficient labeled 2SLS is the instrumental variables estimate of attending a Boston charter with a lottery at any period of time before the outcome listed in the row heading occurred. " 
global note_z		"Indicator variables for a lottery offer on the day of the lottery (initial offer) and lottery offer off of the waitlist (waitlist offer) are the instruments for charter attendance. " 
global note_ccm 	"The control complier mean is labeled CCM. " 
global note_controls	"All regressions control for lottery risk sets and a vector of demographic characteristics including indicators for race, birth year, and baseline special education, English learner, and free or reduced price lunch status, all interacted with gender. " 
global note_sample	"The sample is restricted to students enrolled Boston Public Schools or Boston charter schools at the time of application in the projected high school classes of 2006 to 2017 who are at least 18 by the 2016 general election.  "    
global note_stars	"Robust standard errors are in parentheses (* p$<$0.10 ** p$<$0.05 *** p$<$0.01). " 

*****programs*****

program define endog
cap drop D
cap drop oneminusD
*endogenous variable varies based on outcome
*default is any attendance through 12th grade (including repeats ) for SAT, AP, HS grad 5 and 6, and most voter and college outcomes
qui g D = D_by12
 
if "${Y}"=="twoyearsout_m" |"${Y}"=="twoyearsout_e" |"${Y}"=="ela"|"${Y}"=="math"|"${Y}"=="two_adv_e" |"${Y}"=="two_adv_m"|"${Y}"=="two_prof_e" |"${Y}"=="two_prof_m"{
	qui replace D = D_within2
	}
else if "${Y}"=="totattend9"|"${Y}"=="present9"|"${Y}"=="attendrate9"{
	qui replace D =  D_by10
	}
else if "${Y}"=="c_state_mrawsc10" |"${Y}"=="c_state_erawsc10"|"${Y}"=="ontime10" |"${Y}"=="first_pass"|"${Y}"=="adams_elgh"|"${Y}"=="present10"|"${Y}"=="totattend10"|"${Y}"=="attendrate10"{
	qui replace D =  D_by10
	}
else if "${Y}"=="ontime11"|"${Y}"=="totattend11"|"${Y}"=="attendrate11"{  
	qui replace D =  D_by11
	}

global D D
g oneminusD = 1 - $D

end

program define voterreg

*endogenous variable varies based on outcome
*default is any attendance through 12th grade (including repeates ) for SAT, AP, HS grad 5 and 6, and most voter and college outcomes
*other outcomes overwrite the above for D
endog

global lab_${Y} : variable label ${Y}
qui g ${Y}_Y0=${Y}*oneminusD

qui ivreg2 ${Y}_Y0 (oneminusD = $Z1 $Z2) $covariates $risksets if  voter_sample==1 ///
		, partial($covariates  $risksets) robust /*cluster($clustervar)*/	
		coefccm
qui ivreg2 ${Y} (D = $Z1 $Z2) $covariates $risksets if  voter_sample==1 ///
		, partial($covariates $risksets) robust /*cluster($clustervar)*/	
		coef
	global n_${Y}= string(e(N), "%9.0fc")
  
end

program define voterreg2

*endogenous variable varies based on outcome
*default is any attendance through 12th grade (including repeates ) for SAT, AP, HS grad 5 and 6, and most voter and college outcomes
*other outcomes overwrite the above for D
endog

global lab_${Y} : variable label ${Y}
qui g ${Y}_Y0=${Y}*oneminusD

qui ivreg2 ${Y}_Y0 (oneminusD = $Z1 $Z2) $covariates $risksets if  voter_sample==1 ///
		, partial($covariates  $risksets) robust /*cluster($clustervar)*/	
				local ccm = _b[oneminusD]
qui eststo iv_${Y}:  ivreg2 ${Y} (D = $Z1 $Z2) $covariates $risksets if  voter_sample==1 ///
		, partial($covariates $risksets) robust /*cluster($clustervar)*/	
		qui estadd scalar ccm=`ccm'
end

   
program def voteruse	
use "$data\baseanalysisfile_voter_lotto.dta", clear
*endogenous var
global D D_by12
*Instruments
global Z1 initial_offer_s
global Z2 waitlist_offer_s

g registered_by_21 = 0 
replace registered_by_21= 1 if age_at_registration<=21 
/*
*replace ever_D = 0 if ever_D==.
g ever_D=age_at_registration //need this var
foreach v of varlist ever_pprimary ever_registered ever_primary registered_by_19 ever_vot* ever_gen* ever_pres {
replace `v'  = "1" if `v' =="TRUE"
replace `v'  = "0" if `v' =="FALSE"
destring `v' , replace
}
*/

g repeat = repeat9|repeat10|repeat11|repeat12 if repeat9!=.
	

cd $output

endog
keep if voter_sample==1

end
voteruse
 
program define coef 
	local b = string( _b[${D}], "%9.3f")
	local se = string( _se[${D}], "%9.3f")
	qui esttab
	mat r= r(coefs)
	mat r2 = r["${D}",3]
		local p=r2[1,1]	
	if `p'<0.001{
			local s="***"
			}
	else if `p'<0.01{
			local s="**"
			}	
	else if `p'<0.05{
			local s="*"
			}	
	else if `p'<0.1{
			local s="+"
			}
	else if `p'>=0.1{
			local s=""
			}
		global b_${Y}="`b'`s'"
		global s_${Y}="(`se')"
	
end
program define coef_IO 
	local b = string( _b[${Z1}], "%9.3f")
	local se = string( _se[${Z1}], "%9.3f")
	qui esttab
	mat r= r(coefs)
	mat r2 = r["${Z1}",3]
		local p=r2[1,1]	
	if `p'<0.001{
			local s="***"
			}
	else if `p'<0.01{
			local s="**"
			}	
	else if `p'<0.05{
			local s="*"
			}	
	else if `p'<0.1{
			local s="+"
			}
	else if `p'>=0.1{
			local s=""
			}
		global b1_${Y}="`b'`s'"
		global s1_${Y}="(`se')"
end
program define coef_WO 
	local b = string( _b[${Z2}], "%9.3f")
	local se = string( _se[${Z2}], "%9.3f")
	qui esttab
	mat r= r(coefs)
	mat r2 = r["${Z2}",3]
		local p=r2[1,1]	
	if `p'<0.001{
			local s="***"
			}
	else if `p'<0.01{
			local s="**"
			}	
	else if `p'<0.05{
			local s="*"
			}	
	else if `p'<0.1{
			local s="+"
			}
	else if `p'>=0.1{
			local s=""
			}
		global b2_${Y}="`b'`s'"
		global s2_${Y}="(`se')"
end

program define coefccm
	local b = string( _b[oneminusD], "%9.3f")
	local se = string( _se[oneminusD], "%9.3f")
	qui esttab
	mat r= r(coefs)
	mat r2 = r["oneminusD",3]
		local p=r2[1,1]	
	if `p'<0.001{
			local s="***"
			}
	else if `p'<0.01{
			local s="**"
			}	
	else if `p'<0.05{
			local s="*"
			}	
	else if `p'<0.1{
			local s="+"
			}
	else if `p'>=0.1{
			local s=""
			}
		global bc_${Y}="`b'" // not putting stars for CCM
		global sc_${Y}="(`se')"
		
end

	
}
if $fn_cps ==1{
	
import excel "$data\a2_modified.xlsx", sheet("Education Voting Gap") firstrow clear
	ren A year
	ren thto12thgradenodiploma lessthanHS
	ren HighschoolgraduateorGED HS
	ren Somecollegeorassociatesdegr someCol
	ren Bachelorsdegreeormore BAplus
	
	label var lessthanHS "No HS Diploma"
	label var HS "HS Graduate"
	label var someCol "Some College"
	label var BAplus "BA or more"
	label var year "Year"

graph twoway line BAplus year, lc("${color_1}") ///
	||   line someCol year, lc("${color_2}")  ///
	||   line HS year, lc("${color_3}")  ///
	||   line lessthan year, lc("${color_4}") lp(dash_dot) ///
	text(28 2010  "Less than HS", s(small) c("${color_4}"*1.5)) text(46 2010  "HS Graduate", s(small) c("${color_3}"))  ///
	text(60 2010  "Some College", s(small) c("${color_2}")) text(76 2010  "BA or More", s(small) c("${color_1}"))  ///
	legend(off) ysc(r(0 100)) xsc(r(1964 2020)) xl(1964(4)2020) ysc(extend) xsc(extend) ///
	ytitle("Percent that Voted") //title(U.S. Voting Rates by Education Level Over Time)
			graph export f_cps.pdf, replace 
}
if $tn_voter_pred==1{
  
estimates clear
use  "$data\descriptivesfile_bps9th.dta", clear
keep if atleast18==1
label var baselinefemale "Female"
label var baselineasian "Asian"
label var baselineblack "Black"
label var baselinehisp "Latinx"
label var baselineotherrace "Other race" 
label var baselinewhite "White"
label var baselinesped "Special education"
label var baselinelep "English learner"
label var	baselinefrpl  "Subsidized lunch"
label var   baseline_e "Baseline MCAS ELA"
label var baseline_m "Baseline MCAS Math"
label var   twoyearsout_e "MCAS ELA"
label var twoyearsout_m "MCAS Math"
label var att_any_byY2fall  "Enroll in any college"
label var att_4yr_byY2fall  "Enroll in 4-year college"
label var att_2yr_byY2fall  "Enroll in 2-year college"
label var ever_voted  "Ever voted in MA"
label var first_pos_pres "Voted in first possible presidential"

drop if charter9==1|charter10==1|charter11==1|charter12==1

foreach v in e m{
g baseline_`v'_miss = baseline_`v'==.
su baseline_`v'
replace baseline_`v' =r(mean) if baseline_`v'==.
}


*make sure 8th grade is used as baseline
*predict voting
ren ever_registered er 
ren share_pres ev 
ren first_pos_pres fpp

foreach v of varlist er ev fpp  {
 reghdfe `v'  c.baselinefemale##c.baselineasian c.baselinefemale##c.baselineblack c.baselinefemale##c.baselinehisp ///
	c.baselinefemale##c.baselineotherrace c.baselinefemale##c.baselinesped c.baselinefemale##c.baselinelep ///
		c.baselinefemale##c.baselinefrpl c.baselinefemale##c.c.baseline_m##c.baseline_m##c.baseline_m ///	 	
		c.baselinefemale##c.c.baseline_e##c.baseline_e##c.baseline_e baseline_*_miss ///
		if ( baselinemasscode~=.&hasbaselinedemos==1& inbostonbaseline==1 & proj_year>=2006&proj_year12<=2017&atleast18==1), absorb(year9 baselineyob) ///

estimates store predict_`v'
}
	
voteruse

foreach v in e m{
g baseline_`v'_miss = baseline_`v'==.
su baseline_`v'
replace baseline_`v' =r(mean) if baseline_`v'==.
}


estimates restore predict_er
predict predicted_er, xb  
estimates restore predict_ev
predict predicted_ev, xb  
estimates restore predict_fpp
predict predicted_fpp, xb  

	
estimates clear
foreach y in er ev fpp  {
global Y predicted_`y'
	voterreg2 
	
	
}
ren predicted_fpp pred_fpp
drop predicted*
save "$data/voter_with_predicted.dta", replace



	file open  t	using tn_voter_pred.tex, replace write
	file write t	"\begin{table}[htbp!] \centering" _n "\def\sym#1{\ifmmode^{#1}\else\(^{#1}\)\fi}" _n ///
					"\caption{The Impact of Charter School Attendance on Predicted Voting }" _n "\label{tn_voter_pred}" _n "\small" _n ///
					"\begin{tabular*}{1\textwidth}{@{\extracolsep{\fill}}l*{3}{c}}" _n "\midrule" _n ///
					"&Ever&Share&First Possible\\" _n ///
					"&Registered&Presidential &Presidential   \\" _n ///
					"&(1)&(2)&(3)\\" _n ///
					"\midrule"  _n 
file close t


	esttab iv_* 	using tn_voter_pred.tex, k($D) coef($D "2SLS ") s(ccm N, l( "\hspace{.25cm} CCM"  "" "\hspace{.25cm} \textit{N}"  ) ///
	f(3 %9.0fc) lay(@ `""'  @ )) $opts    

	
	file open  t 	using tn_voter_pred.tex, append write
	file write t 	"\midrule" _n "\end{tabular*}" _n ///
 						"\begin{tabular*}{1\textwidth}{p{6.3in}}" _n ///
					"\footnotesize Notes:  " ///
					"$note_iv" "$note_z" "$note_ccm" "$note_controls" "$note_sample"  ///
					"Predicted voting likelihoods are calculated in the non-charter BPS sample using demographics and baseline test scores, with predicted values applied to the charter lottery population. " "$note_stars" ///
					"\end{tabular*}" _n "\end{table}" _n 
	file close t
	
}
if $tn_covbal==1{
estimates clear
voteruse


label var baselinefemale "Female"
label var baselineasian "Asian"
label var baselineblack "Black"
label var baselinehisp "Latinx"
label var baselineotherrace "Other race" 
label var baselinewhite "White"
label var baselinesped "Special education"
label var baselinelep "English learner"
label var	baselinefrpl  "Free/reduced price lunch"
label var   baseline_e "Baseline MCAS ELA"
label var baseline_m "Baseline MCAS Math"


	file open  t	using tn_covbal.tex, replace write
	file write t	"\begin{table}[htbp!] \centering" _n "\def\sym#1{\ifmmode^{#1}\else\(^{#1}\)\fi}" _n ///
					"\caption{Covariate Balance }" _n "\label{tn_covbal}" _n "\small" _n ///
					"\begin{tabular*}{1\textwidth}{@{\extracolsep{\fill}}l*{3}{c}}" _n "\midrule" _n ///
					"&Non-offered &Initial Offer &Waitlist Offer\\" _n ///
					"&Mean& Differential&Differential\\" _n ///
					"&(1)&(2)&(3)\\" _n ///
					"\midrule" _n	
file close  t	

foreach y of varlist baselinefemale baselineasian baselineblack baselinehisp baselineotherrace baselinewhite ///
	baselinesped baselinelep baselinefrpl $baselinetests  {
global Y `y'
global lab_${Y} : variable label ${Y}
	qui su `y' if $Z1==0&$Z2==0
		global m_`y' = string( r(mean), "%9.3f")
	qui areg `y' $Z1 , absorb(lottogroupYR_boston ) r
		coef_IO
	qui areg `y' $Z2 , absorb(lottogroupYR_boston)  r
		coef_WO
file open  t	using tn_covbal.tex, append write	
file write t  	"\hspace{.5cm} ${lab_`y'} &${m_`y'}& ${b1_`y'}& ${b2_`y'} \\" _n ///	
		"	& &${s1_`y'}& ${s2_`y'} \\" _n "\\" _n		
file close  t			
}
	qui mvreg baselinefemale baselineasian baselineblack baselinehisp   baselinewhite ///
		baselinesped baselinelep baselinefrpl $baselinetests  = $Z1 db_*
	test $Z1
global p1 =string(r(p), "%9.3f")
	qui mvreg baselinefemale baselineasian baselineblack baselinehisp   baselinewhite ///
		baselinesped baselinelep baselinefrpl $baselinetests  = $Z2 db_*
	test $Z2			  
global p2 =string(r(p), "%9.3f")

count 
local n = string( r(N), "%9.0fc")

	file open  t 	using tn_covbal.tex, append write
	file write t 	" &\textit{p}-value& ${p1}& ${p2} \\" _n ///	
					"\midrule" _n "\end{tabular*}" _n ///
					"\begin{tabular*}{1\textwidth}{p{6.3in}}" _n ///
					"\footnotesize Notes:  " ///
					"This table shows means and offer differentials for baseline characteristics. " ///
					"$note_sample" "Column 1 shows the proportion of non-offered students with a given characteristic. " ///
					"Columns 2 and 3 report coefficients from regressions of the student characteristic on initial and waitlist offer dummies, including controls for risk sets, application grade, an (+ p$<$0.10 * p$<$0.05 ** p$<$0.01 ***p$<$0.001). " ///
					"The p-values are from tests of the hypothesis that all coefficients on each offer are zero.  " ///
					"\textit{N}  = `n'. " ///
					"\end{tabular*}" _n "\end{table}" _n 
	file close t

}
if $tn_means==1{
estimates clear
voteruse
keep if atleast18==1&baselinefemale!=.

label var baselinefemale "Female"
label var baselineasian "Asian"
label var baselineblack "Black"
label var baselinehisp "Latinx"
label var baselineotherrace "Other race" 
label var baselinewhite "White"
label var baselinesped "Special education"
label var baselinelep "English learner"
label var	baselinefrpl  "Free/reduced price lunch"
label var   baseline_e "Baseline MCAS ELA"
label var baseline_m "Baseline MCAS Math"
label var baseline_m "Baseline MCAS Math"
label var   twoyearsout_e " MCAS ELA"
label var twoyearsout_m " MCAS Math"
label var att_any_byY2fall  "Enroll in any college"
label var att_4yr_byY2fall  "Enroll in 4-year college"
label var att_2yr_byY2fall  "Enroll in 2-year college"
label var ever_voted  "Ever voted"
label var first_pos_pres "Voted in first possible presidential"
label var share_pres  "Share presidential"

g ever_charter = 0

foreach n of numlist 5/12{
	
replace ever_bcharter =1 if bcharter`n'==1
}

label var ever_bcharter "Attend any charter in grades 5-12"

g applicant = 1
g winner = initial_offer==1|waitlist_offer==1
g loser = applicant==1&winner==0
save applicant, replace

use  "$data\descriptivesfile_bps9th.dta", clear
keep if atleast18==1&baselinefemale!=.
label var baselinefemale "Female"
label var baselineasian "Asian"
label var baselineblack "Black"
label var baselinehisp "Latinx"
label var baselineotherrace "Other race" 
label var baselinewhite "White"
label var baselinesped "Special education"
label var baselinelep "English learner"
label var	baselinefrpl  "Subsidized lunch"
label var   baseline_e "Baseline MCAS ELA"
label var baseline_m "Baseline MCAS Math"
label var   twoyearsout_e "MCAS ELA"
label var twoyearsout_m "MCAS Math"
label var att_any_byY2fall  "Enroll in any college"
label var att_4yr_byY2fall  "Enroll in 4-year college"
label var att_2yr_byY2fall  "Enroll in 2-year college"
label var ever_voted  "Ever voted"
label var first_pos_pres "Voted in first possible presidential"
label var ever_pres  "Ever voted presidential"
label var share_pres "Share of presidential elections"

g ever_bcharter = 0

foreach n of numlist 5/12{
	
replace ever_bcharter =1 if bcharter`n'==1
}

label var ever_bcharter "Attend any charter in grades 5-12"

g bps = 1

save bps, replace

use  "$data\descriptivesfile_ma9th.dta", clear
keep if atleast18==1 &baselinefemale!=.
label var baselinefemale "Female"
label var baselineasian "Asian"
label var baselineblack "Black"
label var baselinehisp "Latinx"
label var baselineotherrace "Other race" 
label var baselinewhite "White"
label var baselinesped "Special education"
label var baselinelep "English learner"
label var	baselinefrpl  "Subsidized lunch"
label var   baseline_e "Baseline MCAS ELA"
label var baseline_m "Baseline MCAS Math"
label var   twoyearsout_e "MCAS ELA"
label var twoyearsout_m "MCAS Math"
label var att_any_byY2fall  "Enroll in any college"
label var att_4yr_byY2fall  "Enroll in 4-year college"
label var att_2yr_byY2fall  "Enroll in 2-year college"
label var ever_voted  "Ever voted"
label var first_pos_pres "Voted in first possible presidential"
label var ever_pres  "Ever voted presidential"
label var share_pres "Share of presidential elections"

g ever_bcharter = 0

foreach n of numlist 5/12{
	
replace ever_bcharter =1 if bcharter`n'==1
}

label var ever_bcharter "Attend any charter in grades 5-12"

keep if ever_bcharter == 1
g attendee=1
save attendee, replace

*can potentially do this by gender
	file open  t	using tn_means.tex, replace write
	file write t	"\begin{table}[htbp!] \centering" _n "\def\sym#1{\ifmmode^{#1}\else\(^{#1}\)\fi}" _n ///
					"\caption{Sample Characteristics and Outcomes }" _n "\label{tn_means}" _n "\small" _n ///
					"\begin{tabular*}{1\textwidth}{@{\extracolsep{\fill}}l*{3}{c}}" _n "\midrule" _n ///
					"&Boston 		&Lottery &Charter  \\" _n ///
					"&Public Schools & Applicants&Attendees\\" _n ///
					"&(1)&(2)&(3)\\" _n ///
					"\midrule" _n		///
					"(A) Baseline characteristics  &&\\" _n "\cmidrule{1-1}" _n 
file close  t	

foreach y of varlist baselinefemale baselineasian baselineblack baselinehisp baselineotherrace baselinewhite ///
	baselinesped baselinelep baselinefrpl $baselinetests  { 
foreach g in bps applicant attendee /*winner loser*/{
use "`g'.dta", clear
global Y `y'
global lab_${Y} : variable label ${Y}
	qui su `y' if `g'==1
	global m_`g'=string(r(mean), "%9.3f")
	}
	
	
file open  t	using tn_means.tex, append write	
file write t  	"\hspace{.5cm} ${lab_`y'} &${m_bps}& ${m_applicant}& ${m_attendee} \\" _n 
file close  t			
}

file open  t 	using tn_means.tex, append write
file write t	" \cmidrule{1-1}" _n "(B) Charter school enrollment  &&\\" _n "\cmidrule{1-1}" _n
file close  t		

foreach y of varlist ever_bcharter { 
foreach g in bps applicant attendee /*winner loser*/{
use "`g'.dta", clear

global Y `y'
global lab_${Y} : variable label ${Y}
	qui su `y' if `g'==1
	global m_`g'=string(r(mean), "%9.3f")
	}
file open  t	using tn_means.tex, append write	
file write t  	"\hspace{.5cm} ${lab_`y'} &${m_bps}& ${m_applicant}& ${m_attendee} \\" _n 
file close  t			
}

file open  t 	using tn_means.tex, append write
file write t	" \cmidrule{1-1}" _n "(C) Academic outcomes  &&\\" _n "\cmidrule{1-1}" _n
file close  t		

foreach y of varlist twoyearsout_m  twoyearsout_e  took_any  above_s3_any  took_sat score_satreason ///
	hsgrad_4yr hsgrad_5yr  att_any_byY2fall att_4yr_byY2fall att_2yr_byY2fall { 
foreach g in bps  attendee applicant  /* winner loser*/ {
use "`g'.dta", clear

global Y `y'
global lab_${Y} : variable label ${Y}
	qui su `y' if `g'==1
	global m_`g'=string(r(mean), "%9.3f")
	}
file open  t	using tn_means.tex, append write	
file write t  	"\hspace{.5cm} ${lab_`y'} &${m_bps}& ${m_applicant} & ${m_attendee}\\" _n 
file close  t			
}	

file open  t 	using tn_means.tex, append write
file write t	" \cmidrule{1-1}" _n "(D) Voting outcomes  &&\\" _n "\cmidrule{1-1}" _n
file close  t		

foreach y of varlist ever_registered   share_pres  first_pos_pres  { 
foreach g in bps  attendee applicant /* winner loser*/ {
use "`g'.dta", clear

global Y `y'
global lab_${Y} : variable label ${Y}
	qui su `y' if `g'==1
	global m_`g'=string(r(mean), "%9.3f")
	}
file open  t	using tn_means.tex, append write	
file write t  	"\hspace{.5cm} ${lab_`y'} &${m_bps}& ${m_applicant} & ${m_attendee}\\" _n 
file close  t			
}	

use bps.dta, clear
count if baselinefemale!=.
local N_bps = string(r(N), "%9.0fc")
use applicant.dta, clear
count if baselinefemale!=.&applicant==1
local N_applicant = string(r(N), "%9.0fc")
use attendee.dta, clear
count if baselinefemale!=.
local N_attendee = string(r(N), "%9.0fc")
/*count if baselinefemale!=.&winner==1
local N_winner = string(r(N), "%9.0fc")
count if baselinefemale!=.&loser==1
local N_loser = string(r(N), "%9.0fc")*/
	
	file open  t 	using tn_means.tex, append write
	file write t 	"\\"  _n "\textit{N}& `N_bps' &`N_applicant' &`N_attendee' \\ " _n    ///	
					"\midrule" _n "\end{tabular*}" _n ///
					"\begin{tabular*}{1\textwidth}{p{6.3in}}" _n ///
			"\footnotesize Notes:  " ///
					"This table shows demographic characteristics and outcome means, for various samples. " ///
					"The sample in Column 1 is restricted to students who attended Boston Public Schools in 9th grade in the projected high school classes of 2006 to 2017, who are are least 18 by the 2016 general election. " ///
					"The sample in Column 2 is restricted to charter school applicants enrolled Boston Public Schools or Boston charter schools at the time of application in the projected high school classes of 2006 to 2017 who are at least 18 by the 2016 general election.  " ///
			"The sample in Column 3 is restricted to students who attended a Massachusetts school in 9th grade and who ever attended a Boston charter school in grades 5 through 12 in the projected high school classes of 2006 to 2017, who are are least 18 by the 2016 general election. " ///
					"\end{tabular*}" _n "\end{table}" _n 
	file close t
	
	erase bps.dta
	erase applicant.dta
	erase attendee.dta

}
if $tn_lottorecords==1{
use "$raw\saves\school by year files\highplus_audit.dta", clear
replace grade=5 if grade==56	
	g proj_year12=year+13-grade
	label var proj_year12 "Projected HS Graduation Year"
	
	g year_all=1
	foreach y of numlist 2006/2017{
		g year_`y'= (proj_year12==`y')
	}

keep if proj_year12<=2017 //these are the folks that reach college entrance
keep if grade>=4
g waitlist_offer=offer-initial_offer
keep school year* grade sasid initial_offer waitlist_offer apply* late outof disqualified sibling dup unmatched mingrade firstapp proj_year
duplicates drop
drop if school=="CapeCod"|school=="FourRiv"|school=="Global"|school=="Innovation" ///
	|school=="KIPP_Lynn"|school=="PVPA"|school=="Parker"|school=="RisingTide" ///
	|school=="SalemAc" |school=="Sturgis"
		
tab unmatched
gen match = unmatched==0

g tot_records = 0
gen secondapplication = 1 if firstapp==0

local audit_vars tot_records disqualified lateapplicant outofarea sibling unmatched  
local years all 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 

mat L=J(11,13,.)	
local row 1
local col 1

	foreach year of local years {
	preserve
	foreach todrop of local audit_vars {
		
			di "you made it to `todrop' `year'"
			drop if (`todrop'==1 & year_`year'==1)
			count if year_`year'==1
			mat L[`row',`col']=r(N)
			local ++row
			}
				* Get count right for excluding repeat applications		
			keep sasid school grade apply* year*
			duplicates drop
				di "you made it to duplicates `year'"
			count if year_`year'==1
			mat L[`row',`col']=r(N)
			local ++row		
			* Reshaping one record per student
			bys	sasid: keep if _n==1
				di "you made it to reshape `year'"
				count if year_`year'==1
			mat L[`row',`col']=r(N)
			local ++row
			
use "$data\baseanalysisfile_voter_lotto.dta", clear
	g year_all=1
	foreach y of numlist 2006/2017{
		g year_`y'= (proj_year12==`y')
	}
	

keep if proj_year12<=2017 //these are the folks that reach college entrance
keep if grade>=4
keep if boston_sample==1
duplicates drop

			di "you made it to has baseline `year'"
			keep if (hasbaselinedemos==1 & year_`year'==1)
			count if year_`year'==1
			mat L[`row',`col']=r(N)
			local ++row		
			
			di "you made it to in Boston `year'"
			keep if (inbostonbaseline==1 & year_`year'==1)
			count if year_`year'==1
			mat L[`row',`col']=r(N)
			local ++row
			
			//voter sample -- Boston baseline, has baseline demos, at least 18
			di "you made it to at least 18 `year'"
			keep if (voter_sample==1 & year_`year'==1)
			count if year_`year'==1
			mat L[`row',`col']=r(N)
			local ++row
			
			
			
		restore
		local ++col
		local row = 1
		
		}
		
mat list L

mat rownames L  = "Total number of records" "Excluding disqualified" "Excluding late applications" "Excluding out-of-area" ///
	"Excluding siblings" "Excluding unmatched"  "Excluding repeat applications" "Reshaping to student-level" ///
	"Has baseline demographics" "In Boston at baseline" "At least 18 by 2016 election"
* mat c =L[1..1,1..13]

* mat list c

estimates clear
cap file close t
	
	cd $output
	file open  t	using tn_lottorecords1.tex, replace write
	file write t	"\begin{sidewaystable}[htbp!] \centering" _n "\def\sym#1{\ifmmode^{#1}\else\(^{#1}\)\fi}" _n ///
					"\caption{Lottery Records: Sample Restrictions}" _n "\label{tn_lottorecords1}" _n "\small" _n ///
					"\begin{tabular*}{1\textwidth}{@{\extracolsep{\fill}}l*{14}{r}}" _n "\midrule" _n ///
					"&All Years&2006&2007&2008&2009&2010&2011&2012&2013&2014&2015&2016&2017\\"  _n ///
					"&(1)&(2)&(3)&(4)&(5)&(6)&(7)&(8)&(9)&(10)&(11)&(12)&(13)\\" _n ///
					"\midrule" _n 
	file close t	
	esttab m(L, f(%10.0fc)) using tn_lottorecords1.tex, a f plain coll(none) nodep nomti
	file open  t 	using tn_lottorecords1.tex, append write
	file write t 	"\midrule" _n "\end{tabular*}" _n ///
					"\begin{tabular*}{1\textwidth}{p{8.4in}}" _n ///
					"\footnotesize Notes: This table shows sample restrictions for the lottery records. Disqualified records are duplicate applications to the same lottery and applications to the wrong grade.  " ///
					"\end{tabular*}" _n "\end{sidewaystable}" _n 	
	file close t	
	
	*middle schools: Brooke Roslindale, Excel East Boston, Mission Hill (formerly Roxbury Prep)
	*5-12/6-12: APR, Boston Collegiate, Boston Prep, Match MS
	*High Schools: Boston Green Academy, City on a Hill, CoaH II, Codman Academy, Match HS
	
foreach s in applyAPR applyBGA applyBosPrep applyBosCol applyMATCH_HS applyMATCH_MS applyCodman applyCoaH applyCoaHII applyExcel applyEdBrooke 	applyRoxPrep {
	count if `s'==1
	local N`s' = string(r(N),"%9.0fc")
}
	cd $output
	file open  t	using tn_lottorecords2.tex, replace write
	file write t	"\begin{sidewaystable}[htbp!] \centering" _n "\def\sym#1{\ifmmode^{#1}\else\(^{#1}\)\fi}" _n ///
					"\caption{Lottery Records: Participation by Schools and Cohorts}" _n "\label{tn_lottorecords2}" _n "\small" _n ///
					"\begin{tabular*}{1\textwidth}{@{\extracolsep{\fill}}l*{7}{c}}" _n "\midrule" _n ///
					"&\multicolumn{3}{c}{Middle Schools}&\multicolumn{4}{c}{Combined Schools (5-12 or 6-12)}\\" _n ///
					"\cline{2-4} \cline{5-8} \\" _n  ///
					"&Brooke			&Excel		&Mission	&Academy of the&Boston &Boston&Match\\"  _n ///
					"&Roslindale (5)	&East Boston (5)&Hill (6) 		&Pacific Rim (5/6) 	&Collegiate (5)&Prep (6)&MS (6)\\"  _n ///
					"&(1)&(2)&(3)&(4)&(5)&(6)&(7)\\" _n ///
					"\midrule" _n ///
"2002&\multirow{4}{*}{No records}&\multirow{6}{*}{No records}	&Yes*	&\multirow{3}{*}{No records}&Yes		&\multirow{2}{*}{Not open}&\multirow{6}{*}{Not open}\\" _n ///
"2003&							&								&Yes*	& 							&Yes		&						&\\" _n ///
"2004&							&								&Yes*	&							&Yes		&Incomplete records		&\\" _n ///
"2005&							&								&Yes	&Yes						&Yes		&Yes**					&\\" _n ///
"2006&				Yes**		&								&Yes	&Yes						&Yes		&Yes					&\\" _n ///
"2007&				Yes			&								&Yes	&Yes						&Yes		&Yes					&\\" _n ///
"2008&				Yes			&Yes							&Yes	&Yes						&Yes		&Yes**					&Yes\\" _n ///
"2009&				Yes			&Yes							&Yes	&Yes						&Yes		&Yes					&Yes\\" _n ///
"2010&Not entry grade			&Too young 						&Yes	&Too young 					&Too young	&Too young				&Yes\\" _n ///
"\textit{N} 	 & `NapplyEdBrooke' 		& `NapplyExcel' 		& `NapplyRoxPrep'& `NapplyAPR'			& `NapplyBosCol'& `NapplyBosPrep' & `NapplyMATCH_MS' \\ " _n ///
					"\midrule" _n ///
					"&&\multicolumn{5}{c}{High Schools}\\" _n ///
					"\cline{3-7}\\ " _n  ///
					"&&Boston Green			&City on a		&City on a 			&Codman			&Match\\"  _n ///
					"&&Academy (9)			&  Hill (9) 	&Hill II (9) 		&Academy (9) 	&HS (9)\\"  _n ///
					"&&(8)&(9)&(10)&(11)&(12)&\\" _n ///
					"\midrule" _n ///
"2002&&\multirow{9}{*}{Not open}&	Yes**			&\multirow{11}{*}{Not open}	&No records							&Yes		&\\" _n ///
"2003&&							&	No records		&							& 	Incomplete records				&Yes		&\\" _n ///
"2004&&							&	Yes				&							&	Yes**							&Yes		&\\" _n ///
"2005&&							&	Yes				&							&\multirow{2}{*}{Incomplete Records}&Yes		&\\" _n ///
"2006&&							&	Yes				&							&									&Yes		&\\" _n ///
"2007&&							&	Yes				&							&No records							&Yes		&\\" _n ///
"2008&&							&Yes				&							&Yes								&Yes		&\\" _n ///
"2009&&							&Yes				&							&Yes								&Yes		&\\" _n ///
"2010&&							&Yes				&							&Yes	 							&Yes		&\\" _n ///
"2011&&		Yes					&Yes				&							&Yes								&\multirow{3}{*}{Not entry grade}	&\\" _n ///
"2012&&		Yes**				&Yes				&							&Yes								&\\" _n ///
"2013&&		Yes					&Yes	 			&Yes**						&Yes								&\\" _n ///
"\textit{N}  	 && `NapplyBGA' 		& `NapplyCoaH' 		& `NapplyCoaHII'		& `NapplyCodman'						& `NapplyMATCH_HS'&  \\" _n ///
	"\midrule" _n "\end{tabular*}" _n ///
					"\begin{tabular*}{1\textwidth}{p{8.4in}}" _n ///
					"\footnotesize Notes: This table shows lottery information by school and application year.  " ///
					"The entry grade is listed in parentheses after the school name.  " ///
					"Some schools have since added grades or changed entry grades outside of the sample period. Brooke, APR, and Match changed their entry grade during the sample period. Mission Hill refers to the original campus of the Roxbury Prep Uncommon Schools network, which was called Roxbury Prep at the time. \\ " _n ///
					" \footnotesize * Indicates that there is no initial offer information. \\ " _n ///
					" \footnotesize ** Indicates that the waitlist was exhausted. " ///
					"\end{tabular*}" _n "\end{sidewaystable}" _n 	
	file close t	

			* * means no initial offer information
			* ** means waitlist exhausted
			* Cohorts after 2009/2010 too young for follow up
			*grade levels indicated in parentheses after school name


}
if $tn_simsmatch==1{
estimates clear
use "$raw\saves\school by year files\highplus_audit.dta", clear
replace grade=5 if grade==56	
	g proj_year12=year+13-grade
	label var proj_year12 "Projected HS Graduation Year"

keep if proj_year12<=2017 //these are the folks that reach college entrance
keep if grade>=4
g waitlist_offer=offer-initial_offer
keep school year grade sasid initial_offer waitlist_offer apply* late outof disqualified sibling dup unmatched mingrade firstapp proj_year
duplicates drop
drop if school=="CapeCod"|school=="FourRiv"|school=="Global"|school=="Innovation" ///
	|school=="KIPP_Lynn"|school=="PVPA"|school=="Parker"|school=="RisingTide" ///
	|school=="SalemAc" |school=="Sturgis"
		
		drop if disqualified==1
	  drop if lateapplicant==1
	  drop if outofarea==1
	  drop if sibling==1
	  
tab unmatched
gen match = unmatched==0


	file open  t	using tn_simsmatch.tex, replace write
	file write t	"\begin{table}[htbp!] \centering" _n "\def\sym#1{\ifmmode^{#1}\else\(^{#1}\)\fi}" _n ///
					"\caption{Match Rate to SIMS }" _n "\label{tn_simsmatch}" _n "\small" _n ///
					"\begin{tabular*}{1\textwidth}{@{\extracolsep{\fill}}l*{4}{c}}" _n "\midrule" _n ///
					"					&Non-offered &Initial Offer &Waitlist Offer&Number of\\" _n ///
					"					&Mean& Differential&Differential&Applications\\" _n ///
					"Projected HS Class&(1)&(2)&(3)&(4)\\" _n ///
					"\midrule" _n	
file close  t	

global Y match
*by cohort

global Z1 initial_offer
global Z2 waitlist_offer
foreach y of numlist 2006/2017{
qui su match if initial_offer==0&waitlist_offer==0 & proj_year12==`y'
		global m_`y' = string( r(mean), "%9.3f")
	qui areg match initial_offer  if proj_year12==`y', absorb(school) r
		coef_IO
	qui areg match waitlist_offer  if proj_year12==`y', absorb(school) r
		coef_WO
	count if proj_year12==`y'
	local n = string( r(N), "%9.0fc")
file open  t	using tn_simsmatch.tex, append write	
file write t  	"\hspace{.5cm} `y' &${m_`y'}& ${b1_match}& ${b2_match} &`n'\\" _n ///	
		"	& &${s1_match}& ${s2_match} \\" _n 	
file close t

}
*in total
qui su match if initial_offer==0&waitlist_offer==0
		global m_`y' = string( r(mean), "%9.3f")
	qui areg match initial_offer , absorb(school) r
		coef_IO
	qui areg match waitlist_offer , absorb(school) r
		coef_WO
	count 
	local n = string( r(N), "%9.0fc")
file open  t	using tn_simsmatch.tex, append write	
file write t  	"\hspace{.5cm} All cohorts &${m_`y'}& ${b1_match}& ${b2_match} &`n'\\" _n ///	
		"	& &${s1_match}& ${s2_match} \\" _n 	
	file write t 	"\midrule" _n "\end{tabular*}" _n ///
					"\begin{tabular*}{1\textwidth}{p{6.3in}}" _n ///
					"\footnotesize Notes:  " ///
					"This table shows the match between lottery records and the SIMS data by projected high school class. " ///
					"The sample excludes disqualified, late, out-of-area, and sibling applications. " ///
					"It includes students who are under the age of 18 at the time of the 2016 election since birth date is only available for students who match to the SIMS data. " ///
					"Individuals can be in the sample multiple times if they apply to multiple schools. " ///
"Columns 2 and 3 report coefficients from regressions of the student characteristic on initial and waitlist offer dummies, including controls for risk sets (+ p$<$0.10 * p$<$0.05 ** p$<$0.01 ***p$<$0.001). " ///
					"\end{tabular*}" _n "\end{table}" _n 
	file close t
	
global Z1 initial_offer_s
global Z2 waitlist_offer_s

}
if $tn_attrition==1{
estimates clear
voteruse
keep if voter_sample==1

merge 1:1 sasid using "$data_clean/sent_to_nsc.dta", nogen keep(1 3)
replace sent_to_nsc=0 if sent_to_nsc==.

foreach s in e m{
	g have_`s'=twoyearsout_`s'!=.
	}
g present_12 = masscode12!=.

label var have_e "Has ELA score (2 years after lottery)"
label var have_m "Has math score (2 years after lottery)"
label var present_12 "Present in 12th grade in data"
label var sent_to_nsc "Sent to NSC"


	file open  t	using tn_attrition.tex, replace write
	file write t	"\begin{table}[htbp!] \centering" _n "\def\sym#1{\ifmmode^{#1}\else\(^{#1}\)\fi}" _n ///
					"\caption{Attrition }" _n "\label{tn_attrition}" _n ///
					"\begin{tabular*}{1\textwidth}{@{\extracolsep{\fill}}l*{3}{c}}" _n "\midrule" _n "\small" _n ///
					"&Fraction of Non- &Initial Offer &Waitlist Offer\\" _n ///
					"&Offered With Outcome& Differential&Differential\\" _n ///
					"&(1)&(2)&(3)\\" _n ///
					"\midrule" _n	
file close  t	

foreach y of varlist have_e have_m present_12 sent_to_nsc {
global Y `y'
global lab_${Y} : variable label ${Y}
qui su `y' if $Z1==0&$Z2==0
		global m_`y' = string( r(mean), "%9.3f")
	areg `y' $Z1 , absorb(lottogroupYR_boston) r
		coef_IO
	areg `y' $Z2 , absorb(lottogroupYR_boston) r
		coef_WO
file open  t	using tn_attrition.tex, append write	
file write t  	"\hspace{.5cm} ${lab_`y'} &${m_`y'}& ${b1_`y'}& ${b2_`y'} \\" _n ///	
		"	& &${s1_`y'}& ${s2_`y'} \\" _n "\\" _n		
file close  t			
}

count 
local n = string( r(N), "%9.0fc")
	file open  t 	using tn_attrition.tex, append write
	file write t 	"\midrule" _n "\end{tabular*}" _n ///
					"\begin{tabular*}{1\textwidth}{p{6.3in}}" _n ///
					"\footnotesize Notes:  " ///
					"This table shows follow-up rates for MCAS scores two years after charter application, presence in the data in 12th grade, and an indicator for being sent to the NSC to be matched to college outcome data for Boston charter school applicants. " ///
					"$note_sample" "Column 1 shows the proportion of non-offered students with a given outcome. " ///
"Columns 2 and 3 report coefficients from regressions of the student characteristic on initial and waitlist offer dummies, including controls for risk sets (* p$<$0.10 ** p$<$0.05 *** p$<$0.01 ). " ///
					"\textit{N} = `n'. " ///
					"\end{tabular*}" _n "\end{table}" _n 
	file close t

}
if $tn_first_stage == 1{
estimates clear
voteruse

count 
local n = string( r(N), "%9.0fc")

label var D_by12 "Ever attend"
label var blottocharteryears "Years"
global Y 

	file open  t	using tn_firststage.tex, replace write
	file write t	"\begin{table}[htbp!] \centering" _n "\def\sym#1{\ifmmode^{#1}\else\(^{#1}\)\fi}" _n ///
					"\caption{The Impact of Charter School Offers on Charter Attendance  }" _n "\label{tn_firststage}" _n "\small" _n ///
					"\begin{tabular*}{1\textwidth}{@{\extracolsep{\fill}}l*{3}{c}}" _n "\midrule" _n ///
					"&Non-offered &Initial  &Waitlist \\" _n ///
					"&Mean& Offer&Offer\\" _n ///
					"&(1)&(2)&(3)\\" _n ///
					"\midrule" _n		
					file close t

	qui su D_by12 if $Z1==0&$Z2==0
		global m = string( r(mean), "%9.3f")
qui reg D_by12 $Z1 $Z2 $covariates $risksets if  voter_sample==1 ,  robust 
	coef_IO
	coef_WO

file open  t	using tn_firststage.tex, append write
file write t  	"\hspace{.5cm} Ever attend charter &${m}& ${b1_}& ${b2_} \\" _n ///	
		"	& & ${s1_} & ${s2_} \\" _n "\\" _n 
file close t

	qui su blottocharteryears if $Z1==0&$Z2==0
		global m = string( r(mean), "%9.3f")
qui reg blottocharteryears $Z1 $Z2 $covariates $risksets if  voter_sample==1 ,  robust 
	coef_IO
	coef_WO

file open  t	using tn_firststage.tex, append write
file write t  	"\hspace{.5cm} Years attended charter  &${m}& ${b1_}& ${b2_} \\" _n ///	
		"	& & ${s1_} & ${s2_} \\" _n "\\" _n  
file close t
	
file open  t	using tn_firststage.tex, append write
file write t "\midrule" _n "\end{tabular*}" _n ///
					"\begin{tabular*}{1\textwidth}{p{6.3in}}" _n ///
					"\footnotesize Notes:  " ///
					"This table shows the impact of a charter school offer on charter school attendance. " ///
					"$note_sample" "Column 1 shows the proportion of non-offered students with a given dimension of charter school attendance. " ///
					"Columns 2 and 3 report coefficients from regressions of charter attendance on initial and waitlist offer dummies, including controls for demographic characteristics and risk sets. " ///
					"$note_stars" ///
					"\textit{N}  = `n'. " ///
					"\end{tabular*}" _n "\end{table}" _n 
	file close t
		
	}	
if $tn_attend_susp == 1{
estimates clear

voteruse

foreach n of numlist 9/12{
	replace day_suspension`n'=0 if day_suspension`n'==.&present`n'==1
}
g day_tot = day_suspension9 + day_suspension10+  day_suspension11+ day_suspension12

foreach v of varlist day_suspension9 day_suspension10 day_suspension11 day_suspension12 day_tot {
	g e`v' = (`v'>0) if `v'!=.
}


foreach y of varlist eday_suspension9 eday_suspension10 eday_suspension11 eday_suspension12 eday_tot day_suspension9 day_suspension10 day_suspension11 day_suspension12 day_tot  {
global Y `y'
	qui ivreg2 ${Y} (D = $Z1 $Z2) $covariates $risksets if  voter_sample==1 ///
		, partial($covariates $risksets) robust rf saverfp(rf_) /*cluster($clustervar)*/
			qui estimates restore rf_$Y
		qui su ${Y} if $Z1==0&$Z2==0
		qui estadd scalar m=r(mean)		
		voterreg2 
	
}

	file open  t	using tn_susp.tex, replace write
	file write t	"\begin{table}[htbp!] \centering" _n "\def\sym#1{\ifmmode^{#1}\else\(^{#1}\)\fi}" _n ///
					"\caption{The Impact of Charter School Attendance on High School Suspensions }" _n "\label{tn_susp}" _n "\small" _n ///
					"\begin{tabular*}{1\textwidth}{@{\extracolsep{\fill}}l*{5}{c}}" _n "\midrule" _n ///
					"&9th&10th&11th  &12th &All High\\" _n ///
					"&Grade&Grade&Grade&Grade &School\\" _n ///
					"&(1)&(2)&(3)&(4)&(5)\\" _n ///
					"\midrule"  _n ///
					"(A) Ever Suspended  &&\\" _n "\cmidrule{1-1}" _n "\textit{Reduced Form}\\" _n
file close t

		esttab rf_e* 	using tn_susp.tex, k($Z1 $Z2) coef($Z1 "Initial Offer" $Z2 "Waitlist Offer" ) s(m, l( "\hspace{.25cm} Non-offered mean" ) f(3 ) lay( @ `""')) $opts  
	file open  t	using tn_susp.tex, append write
file write t "\textit{Second Stage}\\" _n
file close t 
esttab iv_e* 	using tn_susp.tex, k($D) coef($D "2SLS ") 		s(ccm N, l( "\hspace{.25cm} CCM"  ""  "\hspace{.25cm} \textit{N}"    ) f(3 %9.0fc) lay(@ `""'  @ `""'  )) $opts  


 file open  t	using tn_susp.tex, append write	
file write t	" \cmidrule{1-1}" _n "(B) Days Suspended  &&\\" _n "\cmidrule{1-1}" _n "\textit{Reduced Form}\\" _n
file close t
 		esttab rf_day* using	 tn_susp.tex, k($Z1 $Z2) coef($Z1 "Initial Offer" $Z2 "Waitlist Offer" ) s(m, l( "\hspace{.25cm} Non-offered mean" ) f(3 ) lay( @ `""')) $opts  
	file open  t	using tn_attend.tex, append write
file write t "\textit{Second Stage}\\" _n
file close t 
	esttab iv_day* 	using tn_susp.tex, k($D) coef($D "2SLS") s(ccm N, l( "\hspace{.25cm} CCM"    ""  "\hspace{.25cm} \textit{N}"  ) f(3 %9.0fc) lay(@ `""'   @  )) $opts 
	file open  t 	using tn_susp.tex, append write
	file write t 		"\midrule" _n "\end{tabular*}" _n ///
					"\begin{tabular*}{1\textwidth}{p{6.3in}}" _n ///
					"\footnotesize Notes:  " ///
					"$note_iv" "$note_z" "$note_ccm" "$note_controls" "$note_sample"  ///
					 "$note_stars" ///
					"\end{tabular*}" _n "\end{table}" _n 
	file close t
		

estimates clear

voteruse

foreach y of varlist totattend9 totattend10 totattend11 totattend12 totattendhs attendrate9 attendrate10 attendrate11 attendrate12 attendratehs present9 present10 present11 present12 presenths  {
global Y `y'
	qui ivreg2 ${Y} (D = $Z1 $Z2) $covariates $risksets if  voter_sample==1 ///
		, partial($covariates $risksets) robust rf saverfp(rf_) /*cluster($clustervar)*/
		qui 	estimates restore rf_$Y
		qui su ${Y} if $Z1==0&$Z2==0
		qui estadd scalar m=r(mean)		
		voterreg2 
	
}

	file open  t	using tn_attend.tex, replace write
	file write t	"\begin{table}[htbp!] \centering" _n "\def\sym#1{\ifmmode^{#1}\else\(^{#1}\)\fi}" _n ///
					"\caption{The Impact of Charter School Attendance on High School  Days Attended }" _n "\label{tn_attend}" _n "\small" _n ///
					"\begin{tabular*}{1\textwidth}{@{\extracolsep{\fill}}l*{5}{c}}" _n "\midrule" _n ///
					"&9th&10th&11th  &12th &All High\\" _n ///
					"&Grade&Grade&Grade&Grade &School\\" _n ///
					"&(1)&(2)&(3)&(4)&(5)\\" _n ///
					"\midrule"  _n ///
					"(A) Days Attended  &&\\" _n "\cmidrule{1-1}" _n "\textit{Reduced Form}\\" _n
file close t

		esttab rf_totattend* 	using tn_attend.tex, k($Z1 $Z2) coef($Z1 "Initial Offer" $Z2 "Waitlist Offer" ) s(m, l( "\hspace{.25cm} Non-offered mean" ) f(3 ) lay( @ `""')) $opts  
	file open  t	using tn_attend.tex, append write
file write t "\textit{Second Stage}\\" _n
file close t 
esttab iv_totattend* 	using tn_attend.tex, k($D) coef($D "2SLS ") 		s(ccm N, l( "\hspace{.25cm} CCM" ""  "\hspace{.25cm} \textit{N}"  ) f(3 %9.0fc) lay(@ `""'  @ `""'  )) $opts  


 file open  t	using tn_attend.tex, append write	
file write t	" \cmidrule{1-1}" _n "(B) Present in Data  &&\\" _n "\cmidrule{1-1}" _n "\textit{Reduced Form}\\" _n
file close t
 		esttab rf_present* 	using tn_attend.tex, k($Z1 $Z2) coef($Z1 "Initial Offer" $Z2 "Waitlist Offer" ) s(m, l( "\hspace{.25cm} Non-offered mean" ) f(3 ) lay( @ `""')) $opts  
	file open  t	using tn_attend.tex, append write
file write t "\textit{Second Stage}\\" _n
file close t 
	esttab iv_present* 	using tn_attend.tex, k($D) coef($D "2SLS") s(ccm N, l( "\hspace{.25cm} CCM"  ""  "\hspace{.25cm} \textit{N}"  ) f(3 %9.0fc) lay(@ `""'   @  )) $opts 
	file open  t 	using tn_attend.tex, append write
	file write t 		"\midrule" _n "\end{tabular*}" _n ///
					"\begin{tabular*}{1\textwidth}{p{6.3in}}" _n ///
					"\footnotesize Notes:  " ///
					"$note_iv" "$note_z" "$note_ccm" "$note_controls" "$note_sample"  ///
					 "$note_stars" ///
					"\end{tabular*}" _n "\end{table}" _n 
	file close t
		
	}			

if $tn_academic == 1{
estimates clear
voteruse

foreach y of varlist twoyearsout_m  twoyearsout_e took_any N_aps_taken above_s3_any  took_ushistgov above_s3_ushistgov took_sat score_satreason {

global Y `y'
	voterreg2 
	
	qui ivreg2 ${Y} (D = $Z1 $Z2) $covariates $risksets if  voter_sample==1 ///
		, partial($covariates $risksets) robust rf saverfp(rf_) /*cluster($clustervar)*/
			estimates restore rf_$Y
		qui su ${Y} if $Z1==0&$Z2==0
		estadd scalar m=r(mean)	
	
}

	file open  t	using tn_academic.tex, replace write
	file write t	"\begin{sidewaystable}[htbp!] \centering" _n "\def\sym#1{\ifmmode^{#1}\else\(^{#1}\)\fi}" _n ///
					"\caption{The Impact of Charter School Offers and Attendance on Academics }" _n "\label{tn_academic}" _n "\small" _n ///
					"\begin{tabular*}{1\textwidth}{@{\extracolsep{\fill}}l*{9}{c}}" _n "\midrule" _n ///
						"&\multicolumn{2}{c}{MCAS}&\multicolumn{5}{c}{Advanced Placement (AP)}&\multicolumn{2}{c}{SAT} \\" _n ///
						"\cline{2-3} \cline{4-8} \cline{9-10} \\" _n ///
					"&		&	& Took & &&Took&Score 3+&	&Reasoning \\" _n ///
					"&Math	&ELA &Any&Number&Score 3+&US Hist&US Hist&Took	& Score\\" _n ///
					"&Score&Score& AP&of APs&Any AP&or Gov't&or Gov't&SAT&(1600)\\" _n ///
					"&(1)&(2)&(3)&(4)&(5)&(6)&(7)&(8)&(9)\\" _n ///
					"\midrule"  _n	"\textit{Reduced Form}\\" _n			
	file close t

	esttab rf_* 	using tn_academic.tex, k($Z1 $Z2) coef($Z1 "Initial Offer" $Z2 "Waitlist Offer" ) s(m, l( "\hspace{.25cm} Non-offered mean" ) f(3 ) lay( @ `""')) $opts  
		file open  t	using tn_academic.tex, append write
file write t "\textit{Second Stage}\\" _n
file close t 
	esttab iv_* 	using tn_academic.tex, k($D) coef($D "2SLS ") 			s(ccm N, l( "\hspace{.25cm} CCM"  "" "\hspace{.25cm} \textit{N}" "" ) f(3 %9.0fc) lay(@ `""'  @ )) $opts  
	
file open  t 	using tn_academic.tex, append write
file write t "\midrule" _n "\end{tabular*}" _n ///
					"\begin{tabular*}{1\textwidth}{p{8.4in}}" _n ///
					"\footnotesize Notes:  " ///
					"$note_rf" "$note_iv" "$note_z" "$note_ccm" "$note_controls" "$note_sample"  ///
					"MCAS scores are for the exam two years after the charter school lottery. " ///
					"The estimates reported here are for the first attempt at the MCAS. " ///
					"AP and SAT outcomes are available for the class of 2007 and later. " ///
					"\end{tabular*}" _n "\end{sidewaystable}" _n 
	file close t
	
	
	file open  t	using tn_hsprogress.tex, replace write
	file write t	"\begin{sidewaystable}[htbp!] \centering" _n "\def\sym#1{\ifmmode^{#1}\else\(^{#1}\)\fi}" _n ///
					"\caption{The Impact of Charter School Offers and Attendance on High School Progress }" _n "\label{tn_hsprogress}" _n "\small" _n ///
					"\begin{tabular*}{1\textwidth}{@{\extracolsep{\fill}}l*{7}{c}}" _n "\midrule" _n ///
				"&\multicolumn{4}{c}{High School Progress}&\multicolumn{3}{c}{High School Graduation} \\" _n ///
						"\cline{2-5} \cline{6-8}  \\" _n ///
						"&On-time&On-time &On-time&Repeat&4&5&6\\" _n ///
						"&10th&11th&12th&Grade&year&year&year\\" _n ///
					"&(1)&(2)&(3)&(4)&(5)&(6)&(7)\\" _n ///
					"\midrule"  _n	"\textit{Reduced Form}\\" _n			
	file close t

estimates clear
voteruse

foreach y of varlist  ontime10 ontime11 ontime12  repeat  hsgrad_4yr hsgrad_5yr hsgrad_6yr  {

global Y `y'
	qui ivreg2 ${Y} (D = $Z1 $Z2) $covariates $risksets if  voter_sample==1 ///
		, partial($covariates $risksets) robust rf saverfp(rf_) /*cluster($clustervar)*/
			estimates restore rf_$Y
		qui su ${Y} if $Z1==0&$Z2==0
		estadd scalar m=r(mean)		
		voterreg2 
	
}
	esttab rf_* 	using tn_hsprogress.tex, k($Z1 $Z2) coef($Z1 "Initial Offer" $Z2 "Waitlist Offer" ) s(m, l( "\hspace{.25cm} Non-offered mean" ) f(3 ) lay( @ `""')) $opts  
	file open  t	using tn_hsprogress.tex, append write
file write t "\textit{Second Stage}" _n
file close t 
	esttab iv_* 	using tn_hsprogress.tex, k($D) coef($D "2SLS ") 			s(ccm N, l( "\hspace{.25cm} CCM" ""  "\hspace{.25cm} \textit{N}" "" ) f(3 %9.0fc) lay(@ `""'  @  )) $opts    
	
file open  t 	using tn_hsprogress.tex, append write
	file write t "\midrule" _n "\end{tabular*}" _n ///
	"\begin{tabular*}{1\textwidth}{p{8.4in}}" _n ///
					"\footnotesize Notes:  " ///
					"$note_rf" "$note_iv" "$note_z" "$note_ccm" "$note_controls" "$note_sample"  ///
					"\end{tabular*}" _n "\end{sidewaystable}" _n 
	file close t
	
	file open  t	using tn_attainment.tex, replace write
	file write t	"\begin{sidewaystable}[htbp!] \centering" _n "\def\sym#1{\ifmmode^{#1}\else\(^{#1}\)\fi}" _n ///
					"\caption{The Impact of Charter School Offers and Attendance on College }" _n "\label{tn_attainment}" _n "\small" _n ///
					"\begin{tabular*}{1\textwidth}{@{\extracolsep{\fill}}l*{8}{c}}" _n "\midrule" _n ///
				"&\multicolumn{3}{c}{College Enrollment}&\multicolumn{3}{c}{Degree Completion} &\multicolumn{2}{c}{Years of Education}\\" _n ///
						"\cline{2-4} \cline{5-7}  \cline{8-9} \\" _n ///
						"&&4&2&&&&By First & \\" _n ///
						"&Any&year&year&Any&BA&AA&Pos. Pres. & Ever \\" _n ///
					"&(1)&(2)&(3)&(4)&(5)&(6)&(7)&(8)\\" _n ///
					"\midrule"  _n	"\textit{Reduced Form}\\" _n			
	file close t

estimates clear
voteruse

foreach y of varlist  att_any_byY2fall att_4yr_byY2fall att_2yr_byY2fall cmp_any_byY6 cmp_BA_byY6 cmp_AA_byY6 yearsbyfirst yearsever {
cap drop *Y0
global Y `y'
	qui ivreg2 ${Y} (D = $Z1 $Z2) $covariates $risksets if  voter_sample==1 ///
		, partial($covariates $risksets) robust rf saverfp(rf_) /*cluster($clustervar)*/
		qui estimates restore rf_$Y
		qui su ${Y} if $Z1==0&$Z2==0
		qui estadd scalar m=r(mean)		
		voterreg2 
	
}
	esttab rf_* 	using tn_attainment.tex, k($Z1 $Z2) coef($Z1 "Initial Offer" $Z2 "Waitlist Offer" ) s(m, l( "\hspace{.25cm} Non-offered mean" ) f(3 ) lay( @ `""')) $opts  
	file open  t	using tn_attainment.tex, append write
file write t "\textit{Second Stage}" _n
file close t 
	esttab iv_* 	using tn_attainment.tex, k($D) coef($D "2SLS ") 			s(ccm N, l( "\hspace{.25cm} CCM" ""  "\hspace{.25cm} \textit{N}" "" ) f(3 %9.0fc) lay(@ `""'  @  )) $opts    
	
file open  t 	using tn_attainment.tex, append write
	file write t "\midrule" _n "\end{tabular*}" _n ///
	"\begin{tabular*}{1\textwidth}{p{8.4in}}" _n ///
					"\footnotesize Notes:  " ///
					"$note_rf" "$note_iv" "$note_z" "$note_ccm" "$note_controls" "$note_sample"  ///
					"College enrollment is defined enrollment for at least one semester of college within 18 months of expected high school graduation. Degree completion is within 6 years of projected high school graduation. It is possible to complete both an AA and a BA. " ///
					"\end{tabular*}" _n "\end{sidewaystable}" _n 
	file close t
	
 
	}	
if $fn_academic == 1{
estimates clear
clear
g save = 1
save acad, replace

voteruse
  
g two_m_above = twoyearsout_m>=0
g two_e_above = twoyearsout_e>=0

foreach y of varlist att_any_byY2fall att_2yr_byY2fall att_4yr_byY2fall hsgrad_6yr hsgrad_5yr hsgrad_4yr ontime10 ontime11 ontime12 repeat totattend9 totattend10 totattend11 totattend12 above_median_satreason  took_sat above_s3_any took_any two_e_above two_m_above twoyearsout_m twoyearsout_e {
global Y `y'
endog

global lab_${Y} : variable label ${Y}
qui g ${Y}_Y0=${Y}*oneminusD

qui eststo iv_${Y}: ivreg2 ${Y} (D = $Z1 $Z2) $covariates $risksets if  voter_sample==1 , partial($covariates  $risksets) robust
preserve
	qui regsave using acad, ci pval addlabel(outcome, `y', sample,  all)  append
restore	
qui ivreg2 ${Y}_Y0 (oneminusD = $Z1 $Z2) $covariates $risksets if  voter_sample==1 , partial($covariates  $risksets) robust
preserve
	qui regsave using acad, ci pval addlabel(outcome, `y', sample,  all)  append
restore
}


*graph version

use "$output/acad.dta", clear
drop save r2  N
g count = _n

reshape wide coef ci_* stderr pval* count, i(outcome sample) j(var) string

g star  = ""
replace star = "*" if pvalD<0.1
replace star = "**" if pvalD<0.05
replace star = "***" if pvalD<0.01
*replace star = "***" if pvalD<0.001

tostring coefD, generate(te) format( "%9.3fc") force
tostring stderrD, generate(se) format( "%9.3fc") force
g impact = "LATE: " + te + star + " (" + se + ")"
g impact1 = "LATE: "  + te + star 
g impact2 = "(" + se + ")"

drop stderr*

foreach v of varlist coefD ci_lowerD ci_upperD {
	replace `v' = `v'+coefoneminusD
}
reshape long coef ci_lower ci_upper count , i(outcome sample impact*) j(var) string

replace var = "TCM" if var =="D"
replace var = "CCM" if var =="oneminusD"

local counter = 2
qui levelsof outcome, local(vars)
		foreach v of local vars{
			global `v'_all: di impact[`counter']
			global `v'_all1: di impact1[`counter']
			global `v'_all2: di impact2[`counter']
			local ++counter
			local ++counter		
	}
	
sort sample count var

preserve
	keep if (outcome=="twoyearsout_m" |outcome=="twoyearsout_e" ) 
	replace outcome = "1" if outcome=="twoyearsout_m"
	replace outcome = "2" if outcome=="twoyearsout_e"
	destring outcome, replace
	sort outcome var
	drop sample*
	g sample = outcome - .175 if var=="CCM"
	replace sample = outcome + .175 if var=="TCM"

	twoway bar coef sample if var=="CCM", barw(.34) fc("${color_c}%70")  lc("${color_c}") lw(medthick) ///
			|| bar coef sample if var=="TCM", barw(.34) fc("${color_t}%70")  lc("${color_t}") lw(medthick) ///
			|| rcap ci_lower ci_upper sample if var=="CCM",  lc("${color_c}") lw(medium) ///
			|| rcap ci_lower ci_upper sample if var=="TCM",  lc("${color_t}") lw(medium) , ///
			|| scatter coef sample if var=="CCM", ms(i) mlabel(coef) mlabc(black) mlabp(8) mlabf(%9.2f) mlabs(small)  ///		
			|| scatter coef sample if var=="TCM" & coef>0, ms(i) mlabel(coef) mlabc(black) mlabp(10) mlabf(%9.2f) mlabs(small)  ///		
			|| scatter coef sample if var=="TCM" & coef<0, ms(i) mlabel(coef) mlabc(black) mlabp(8) mlabf(%9.2f) mlabs(small)  ///		
			yscale(r(-.5 .2)) ysc(extend) xsc(extend) xsc(r(.05 2.95)) ///
			yl(-.5(.25).25, labs(medsmall)) ytitle("Score (Standard Deviations)", size(medium)) ///
			xlabel(1 `" "{bf:Math MCAS}" "$twoyearsout_m_all1" "$twoyearsout_m_all2" "' ///
					 2 `"  "{bf:ELA MCAS}" "$twoyearsout_e_all1" "$twoyearsout_e_all2" "' , labs(medium))  ///
			title("`lab'", size(medlarge)) xtitle("") title(A. MCAS) ///
			legend(pos(6) row(1) order(1 "Untreated Compliers" 2 "Treated Compliers") size(medium)) ///
			name(key_mcas, replace)
restore

preserve
	keep if (outcome=="totattend9" |outcome=="totattend10"|outcome=="totattend11"|outcome=="totattend12" ) 
	replace outcome = "1" if outcome=="totattend9"
	replace outcome = "2" if outcome=="totattend10"
	replace outcome = "3" if outcome=="totattend11"
	replace outcome = "4" if outcome=="totattend12"
	destring outcome, replace
	sort outcome var
	drop sample*
	g sample = outcome - .175 if var=="CCM"
	replace sample = outcome + .175 if var=="TCM"

	twoway bar coef sample if var=="CCM", barw(.34) fc("${color_c}%70")  lc("${color_c}") lw(medthick) ///
			|| bar coef sample if var=="TCM", barw(.34) fc("${color_t}%70")  lc("${color_t}") lw(medthick) ///
			|| rcap ci_lower ci_upper sample if var=="CCM",  lc("${color_c}") lw(medium) ///
			|| rcap ci_lower ci_upper sample if var=="TCM",  lc("${color_t}") lw(medium) , ///
			|| scatter coef sample if var=="CCM", ms(i) mlabel(coef) mlabc(black) mlabp(10) mlabf(%9.0f) mlabs(small)  ///		
			|| scatter coef sample if var=="TCM" , ms(i) mlabel(coef) mlabc(black) mlabp(10) mlabf(%9.0f) mlabs(small)  ///		
			yscale(r(120 180)) ysc(extend) xsc(extend) ///
			yl(120(30)180, labs(medsmall)) ytitle("Days", size(medium)) ///
			xlabel(1 `" "{bf:9th Grade}" "$totattend9_all1" "$totattend9_all2" "' ///
					 2 `"  "{bf:10th Grade }" "$totattend10_all1" "$totattend10_all2" "' ///
					 3 `"  "{bf:11th Grade}"  "$totattend11_all1"  "$totattend11_all2" "' ///
					 4 `"  "{bf:12th Grade}"  "$totattend12_all1" "$totattend12_all2"  "' , labs(medium)) ///
			title("`lab'", size(medlarge)) xtitle("") title(B. Days of High School Attendance) ///
			legend(pos(6) row(1) order(1 "Untreated Compliers" 2 "Treated Compliers") size(medium)) ///
			name(key_attend, replace)
restore

preserve
	keep if (outcome=="ontime10" |outcome=="ontime11"|outcome=="ontime12"|outcome=="repeat" ) 
	replace outcome = "1" if outcome=="ontime10"
	replace outcome = "2" if outcome=="ontime11"
	replace outcome = "3" if outcome=="ontime12"
	replace outcome = "4" if outcome=="repeat"
	destring outcome, replace
	sort outcome var
	drop sample*
	g sample = outcome - .175 if var=="CCM"
	replace sample = outcome + .175 if var=="TCM"

	twoway bar coef sample if var=="CCM", barw(.34) fc("${color_c}%70")  lc("${color_c}") lw(medthick) ///
			|| bar coef sample if var=="TCM", barw(.34) fc("${color_t}%70")  lc("${color_t}") lw(medthick) ///
			|| rcap ci_lower ci_upper sample if var=="CCM",  lc("${color_c}") lw(medium) ///
			|| rcap ci_lower ci_upper sample if var=="TCM",  lc("${color_t}") lw(medium) , ///
			|| scatter coef sample if var=="CCM", ms(i) mlabel(coef) mlabc(black) mlabp(10) mlabf(%9.2f) mlabs(small)  ///		
			|| scatter coef sample if var=="TCM" , ms(i) mlabel(coef) mlabc(black) mlabp(10) mlabf(%9.2f) mlabs(small)  ///		
			yscale(r(0 .8)) ysc(extend) xsc(extend) ///
			yl(0(.2).8, labs(medsmall)) ytitle("Fraction", size(medium)) ///
			xlabel(1 `" "{bf:Ontime 10th}" "$ontime10_all1" "$ontime10_all2" "' ///
					 2 `"  "{bf:Ontime 11th }" "$ontime11_all1" "$ontime11_all2" "' ///
					 3 `"  "{bf:Ontime 12th}"  "$ontime12_all1"  "$ontime12_all2" "' ///
					 4 `"  "{bf:Repeat Grade}"  "$repeat_all1" "$repeat_all2"  "' , labs(medium)) ///
			title("`lab'", size(medlarge)) xtitle("") title(C. High School Grade Progression) ///
			legend(pos(6) row(1) order(1 "Untreated Compliers" 2 "Treated Compliers") size(medium)) ///
			name(key_on, replace)
restore


preserve
	keep if (outcome=="took_any" |outcome=="above_s3_any" | outcome=="took_sat"| outcome=="above_median_satreason")
	replace outcome = "1" if outcome=="took_any"
	replace outcome = "2" if outcome=="above_s3_any"
	replace outcome = "3" if outcome=="took_sat"
	replace outcome = "4" if outcome=="above_median_satreason"
	destring outcome, replace
	sort outcome var
	drop sample*
	g sample = outcome - .175 if var=="CCM"
	replace sample = outcome + .175 if var=="TCM"

	twoway bar coef sample if var=="CCM", barw(.34) fc("${color_c}%70")  lc("${color_c}") lw(medthick) ///
			|| bar coef sample if var=="TCM", barw(.34) fc("${color_t}%70")  lc("${color_t}") lw(medthick) ///
			|| rcap ci_lower ci_upper sample if var=="CCM",  lc("${color_c}") lw(medium) ///
			|| rcap ci_lower ci_upper sample if var=="TCM",  lc("${color_t}") lw(medium) , ///
			|| scatter coef sample if var=="CCM", ms(i) mlabel(coef) mlabc(black) mlabp(10) mlabf(%9.2f) mlabs(small)  ///		
			|| scatter coef sample if var=="TCM", ms(i) mlabel(coef) mlabc(black) mlabp(10) mlabf(%9.2f) mlabs(small)  ///		
			yscale(r(0 .8)) ysc(extend) xsc(extend) ///
			yl(0(.2).8, labs(medsmall)) ytitle("Fraction", size(medium)) ///
			xlabel(1 `" "{bf:Took Any AP}" "$took_any_all1" "$took_any_all2" "' ///
					 2 `"  "{bf:Any AP 3+ }" "$above_s3_any_all1" "$above_s3_any_all2" "' ///
					 3 `"  "{bf:Took SAT}"  "$took_sat_all1"  "$took_sat_all2" "' ///
					 4 `"  "{bf:SAT Median+}"  "$above_median_satreason_all1" "$above_median_satreason_all2"  "' , labs(medium)) ///
			title("`lab'", size(medlarge)) xtitle("") title(D. AP and SAT) ///
			legend(pos(6) row(1) order(1 "Untreated Compliers" 2 "Treated Compliers") size(medium)) ///
			name(key_test, replace)
restore

preserve
	keep if (outcome=="hsgrad_4yr" |outcome=="hsgrad_5yr" | outcome=="hsgrad_6yr")
	replace outcome = "1" if outcome=="hsgrad_4yr"
	replace outcome = "2" if outcome=="hsgrad_5yr"
	replace outcome = "3" if outcome=="hsgrad_6yr"
	destring outcome, replace
	sort outcome var
	drop sample*
	g sample = outcome - .175 if var=="CCM"
	replace sample = outcome + .175 if var=="TCM"

	twoway bar coef sample if var=="CCM", barw(.34) fc("${color_c}%70")  lc("${color_c}") lw(medthick) ///
			|| bar coef sample if var=="TCM", barw(.34) fc("${color_t}%70")  lc("${color_t}") lw(medthick) ///
			|| rcap ci_lower ci_upper sample if var=="CCM",  lc("${color_c}") lw(medium) ///
			|| rcap ci_lower ci_upper sample if var=="TCM",  lc("${color_t}") lw(medium) , ///
			|| scatter coef sample if var=="CCM", ms(i) mlabel(coef) mlabc(black) mlabp(10) mlabf(%9.2f) mlabs(small)  ///		
			|| scatter coef sample if var=="TCM", ms(i) mlabel(coef) mlabc(black) mlabp(10) mlabf(%9.2f) mlabs(small)  ///		
			yscale(r(0 .8)) ysc(extend) xsc(extend) ///
			yl(0(.2).8, labs(medsmall)) ytitle("Fraction", size(medium)) ///
			xlabel(1 `" "{bf:In 4 Years}" "$hsgrad_4yr_all1" "$hsgrad_4yr_all2" "' ///
					 2 `"  "{bf:In 5 Years }" "$hsgrad_5yr_all1" "$hsgrad_5yr_all2" "' ///
					 3 `"  "{bf:In 6 Years}"  "$hsgrad_6yr_all1"  "$hsgrad_6yr_all2" "', labs(medium)) ///
			title("`lab'", size(medlarge)) xtitle("")  title(E. High School Graduation)  ///
			legend(pos(6) row(1) order(1 "Untreated Compliers" 2 "Treated Compliers") size(medium)) ///
			name(key_hs, replace)
restore

preserve
	keep if (outcome=="att_any_byY2fall" |outcome=="att_4yr_byY2fall" | outcome=="att_2yr_byY2fall") 
	replace outcome = "1" if outcome=="att_any_byY2fall"
	replace outcome = "2" if outcome=="att_4yr_byY2fall"
	replace outcome = "3" if outcome=="att_2yr_byY2fall"
	destring outcome, replace
	sort outcome var
	drop sample*
	g sample = outcome - .175 if var=="CCM"
	replace sample = outcome + .175 if var=="TCM"

	twoway bar coef sample if var=="CCM", barw(.34) fc("${color_c}%70")  lc("${color_c}") lw(medthick) ///
			|| bar coef sample if var=="TCM", barw(.34) fc("${color_t}%70")  lc("${color_t}") lw(medthick) ///
			|| rcap ci_lower ci_upper sample if var=="CCM",  lc("${color_c}") lw(medium) ///
			|| rcap ci_lower ci_upper sample if var=="TCM",  lc("${color_t}") lw(medium) , ///
			|| scatter coef sample if var=="CCM", ms(i) mlabel(coef) mlabc(black) mlabp(10) mlabf(%9.2f) mlabs(small)  ///		
			|| scatter coef sample if var=="TCM", ms(i) mlabel(coef) mlabc(black) mlabp(10) mlabf(%9.2f) mlabs(small)  ///		
			yscale(r(0 .8)) ysc(extend) xsc(extend) ///
			yl(0(.2).8, labs(medsmall)) ytitle("Fraction", size(medium)) ///
				xlabel(1 `" "{bf:Any College}" "$att_any_byY2fall_all1" "$att_any_byY2fall_all2" "' ///
					 2 `"  "{bf:4-Year }" "$att_4yr_byY2fall_all1" "$att_4yr_byY2fall_all2" "' ///
					 3 `"  "{bf:2-Year}"  "$att_2yr_byY2fall_all1"  "$att_2yr_byY2fall_all2" "', labs(medium)) ///
			title("`lab'", size(medlarge)) xtitle("")  title(F. College Enrollment)  ///
			legend(pos(6) row(1) order(1 "Untreated Compliers" 2 "Treated Compliers") size(medium)) ///
			name(key_col, replace)
restore

 grc1leg2 key_mcas key_attend key_on key_test key_hs key_col, row(2) xsize(16.5) ysize(8.25) altshrink
				graph export f_acad.pdf, replace 	
	
	
	
preserve

drop sample
g sample = 1 if outcome =="two_m_above"
replace  sample = 2 if outcome =="two_e_above"
replace sample = 3 if outcome =="took_any"
replace sample = 4 if outcome =="above_s3_any"
replace sample = 5 if outcome =="took_sat"
replace sample = 6 if outcome =="above_median_satreason"
replace sample = 7 if outcome =="hsgrad_4yr"
replace sample = 8 if outcome =="hsgrad_5yr"
replace sample = 9 if outcome =="att_4yr_byY2fall"
sort sample
drop if sample==.

g sample_1 = sample-.2
g sample_2 = sample+.2

g labeler = 0.025

		twoway bar coef sample_1 if var=="CCM", barw(.39) fc("${color_c}%70")  lc("${color_c}") lw(medthick) ///
			|| bar coef sample_2 if var=="TCM", barw(.39) fc("${color_t}%70")  lc("${color_t}") lw(medthick) ///
			|| rcap ci_lower ci_upper sample_1 if var=="CCM",  lc("${color_c}") lw(medium) ///
			|| rcap ci_lower ci_upper sample_2 if var=="TCM",  lc("${color_t}") lw(medium) , ///
			|| scatter labeler sample_1 if var=="CCM", ms(i) mlabel(coef) mlabc(black) mlabp(0) mlabf(%9.2f) mlabs(vsmall)  ///		
			|| scatter labeler sample_2 if var=="TCM", ms(i) mlabel(coef) mlabc(black) mlabp(0)  mlabf(%9.2f) mlabs(vsmall)  ///		
			yscale(r(0 .83)) ysc(extend) xsc(extend) ///
			yl(0(.2).8, labs(medsmall)) ytitle("Fraction", size(medium)) ///
			xlabel(1 `" "{bf:Math MCAS}" "{bf:Above Median}" "$two_m_above_all1" "$two_m_above_all2"  "' /// 
					 2 `"  "{bf:ELA MCAS}" "{bf:Above Median}"  "$two_e_above_all1" $two_e_above_all2" "' ///  
					 3 `"  "{bf:Took}" "{bf:Any AP}"   "$took_any_all1" "$took_any_all2"  "' ///  
					 4 `" "{bf:Any AP}" "{bf:Score 3+}"  "$above_s3_any_all1" "$above_s3_any_all2"  "' /// 
					 5 `"  "{bf:Took}" "{bf:SAT}"  "$took_sat_all1" "$took_sat_all2"  "' /// 
					 6 `"  "{bf:SAT Above}" "{bf:National Median}"  "$above_median_satreason_all1" "$above_median_satreason_all2" "' ///  
					 7 `" "{bf:4-Yr HS}" "{bf:Graduation}"  "$hsgrad_4yr_all1" "$hsgrad_4yr_all2" "' ///  
					 8 `" "{bf:5-Yr HS}" "{bf:Graduation}"  "$hsgrad_5yr_all1" "$hsgrad_5yr_all2" "' ///  
					 9 `" "{bf:Enroll 4-Yr}" "{bf: College}"  "$att_4yr_byY2fall_all1" "$att_4yr_byY2fall_all2" "' ///  
					 , labs(small)) ///
			legend(pos(6) row(1) order(1 "Untreated Compliers" 2 "Treated Compliers") size(medium)) ///
			name(acad, replace) 	xsize(9.5) ysize(4.25)	saving("$output/f_academic.gph", replace)
				graph export f_academic.pdf, replace 
				
restore
								
}	
if $tn_instate_outstate == 1{

estimates clear


voteruse

label var att_any_byY2fall "Any"
label var att_4yr_byY2fall "4-year"
label var att_2yr_byY2fall "2-year"


foreach n of numlist 1/2{
	g att_4yrMA_byY`n'fall =  att_4yrMApub_byY`n'fall +att_4yrMApriv_byY`n'fall
	g att_2yrMA_byY`n'fall = att_2yr_byY`n'fall==1&att_MA_byY`n'fall==1 if  att_2yr_byY`n'fall!=.
foreach d in 2yr 4yr {
	g att_`d'notMA_byY`n'fall =  att_`d'_byY`n'fall-att_`d'MA_byY`n'fall
	}
	}


foreach y of varlist att_any_byY1fall att_4yr_byY1fall att_2yr_byY1fall att_any_byY2fall att_4yr_byY2fall att_2yr_byY2fall {

global Y `y'
	voterreg2 
	
}

	file open  t	using tn_instate_outstate.tex, replace write
	file write t	"\begin{table}[htbp!] \centering" _n "\def\sym#1{\ifmmode^{#1}\else\(^{#1}\)\fi}" _n ///
					"\caption{The Impact of Charter School Attendance on College Enrollment by College Location }" _n "\small" _n "\label{tn_instate_outstate}" _n ///
					"\begin{tabular*}{1\textwidth}{@{\extracolsep{\fill}}l*{6}{c}}" _n "\midrule" _n ///
					"&\multicolumn{3}{c}{Within 6 months}&\multicolumn{3}{c}{Within 18 months } \\" _n ///
						"\cline{2-4} \cline{5-7}  \\" _n ///						
						"&Any&4 year&2 year&Any&4 year&2 year\\" _n ///
					"&(1)&(2)&(3)&(4)&(5)&(6)\\" _n ///
					"\midrule" _n	///
					"(A) All Institutions  &&\\" _n "\cmidrule{1-1}" _n 
file close t

	esttab iv_* 	using tn_instate_outstate.tex, k($D) coef($D "2SLS ") 	s(ccm , l( "\hspace{.25cm} CCM"   ) f(3 ) lay(@    )) $opts 
	
file open  t	using tn_instate_outstate.tex, append write		
file write t	" \cmidrule{1-1}" _n "(B) In Massachusetts  &&\\" _n "\cmidrule{1-1}" _n
file close t

estimates clear
foreach y of varlist att_MA_byY1fall att_4yrMA_byY1fall att_2yrMA_byY1fall att_MA_byY2fall att_4yrMA_byY2fall att_2yrMA_byY2fall {
 
global Y `y'
	voterreg2 
	
}
	esttab iv_* 	using tn_instate_outstate.tex, k($D) coef($D "2SLS ") 	s(ccm , l( "\hspace{.25cm} CCM"   ) f(3 ) lay(@    )) $opts 

	file open  t	using tn_instate_outstate.tex, append write	
file write t	" \cmidrule{1-1}" _n "(C) Out of state   &&\\" _n "\cmidrule{1-1}" _n
file close t

estimates clear

foreach y of varlist  att_out_byY1fall att_4yrnotMA_byY1fall att_2yrnotMA_byY1fall att_out_byY2fall att_4yrnotMA_byY2fall att_2yrnotMA_byY2fall  {
  
global Y `y'
	voterreg2 
}

count 
local n = string( r(N), "%9.0fc")

	esttab iv_* 	using tn_instate_outstate.tex, k($D) coef($D "2SLS ") 		s(ccm , l( "\hspace{.25cm} CCM"   ) f(3 ) lay(@    )) $opts 
	
	
	file open  t 	using tn_instate_outstate.tex, append write
	file write t 		"\midrule" _n "\end{tabular*}" _n ///
					"\begin{tabular*}{1\textwidth}{p{6.3in}}" _n ///
					"\footnotesize Notes:  " ///
					" The notes for this table are the same as in Online Appendix Table \ref{tn_attainment} but for an expanded set of college outcomes. \textit{N} = `n'. "  ///
					"\end{tabular*}" _n "\end{table}" _n 
	file close t
		
	}	

*new analysis
if $f_baseline_peers==1{
	
estimates clear
clear
g save = 1
save peergraph, replace

*get out-of-sample prediction for voting based on BPS
estimates clear
use  "$data\descriptivesfile_bps9th.dta", clear
keep if atleast18==1
label var baselinefemale "Female"
label var baselineasian "Asian"
label var baselineblack "Black"
label var baselinehisp "Latinx"
label var baselineotherrace "Other race" 
label var baselinewhite "White"
label var baselinesped "Special education"
label var baselinelep "English learner"
label var	baselinefrpl  "Subsidized lunch"
label var   baseline_e "Baseline MCAS ELA"
label var baseline_m "Baseline MCAS Math"
label var   twoyearsout_e "MCAS ELA"
label var twoyearsout_m "MCAS Math"
label var att_any_byY2fall  "Enroll in any college"
label var att_4yr_byY2fall  "Enroll in 4-year college"
label var att_2yr_byY2fall  "Enroll in 2-year college"
label var ever_voted  "Ever voted in MA"
label var first_pos_pres "Voted in first possible presidential"

drop if charter9==1|charter10==1|charter11==1|charter12==1

foreach v in e m{
g baseline_`v'_miss = baseline_`v'==.
su baseline_`v'
replace baseline_`v' =r(mean) if baseline_`v'==.
}


*make sure 8th grade is used as baseline
*predict voting
ren first_pos_pres fpp

 reghdfe fpp  c.baselinefemale##c.baselineasian c.baselinefemale##c.baselineblack c.baselinefemale##c.baselinehisp ///
	c.baselinefemale##c.baselineotherrace c.baselinefemale##c.baselinesped c.baselinefemale##c.baselinelep ///
		c.baselinefemale##c.baselinefrpl c.baselinefemale##c.c.baseline_m##c.baseline_m##c.baseline_m ///	 	
		c.baselinefemale##c.c.baseline_e##c.baseline_e##c.baseline_e baseline_*_miss ///
		if ( baselinemasscode~=.&hasbaselinedemos==1& inbostonbaseline==1 & proj_year>=2006&proj_year12<=2017&atleast18==1), absorb(year9 baselineyob) 

estimates store predict_fpp

*get baseline scores 
use  "$data\descriptivesfile_ma9th.dta", clear

*apply prediction
foreach v in e m{
g baseline_`v'_miss = baseline_`v'==.
su baseline_`v'
replace baseline_`v' =r(mean) if baseline_`v'==.
}

estimates restore predict_fpp
predict predicted_fpp, xb  

keep c_state_eraw*  c_state_mraw* attend* sasid   predicted_fpp  

reshape long  c_state_erawsc c_state_mrawsc attend , i(sasid predicted_fpp) j(grade)
keep if grade==4|grade==5|grade==8

ren attend baselinepeer_a_
ren c_state_e baselinepeer_e_
ren c_state_m baselinepeer_m_
ren predicted_fpp baselinepeer_v_

reshape wide  baselinepeer* , i(sasid) j(grade)

tempfile baseline
save "`baseline'"

*define peer groups
use sasid year* masscode* using  "$data\descriptivesfile_ma9th.dta", clear
drop yearap yearsat

reshape long year masscode, i(sasid) j(grade)

drop if year==.&masscode==.
format masscode %12.0f
merge m:1 sasid using "`baseline'", nogen
drop sasid
collapse (mean) baseline*, by(year grade masscode)

	*generate vars for where people are in the 4 years after the lottery
	foreach t in year masscode grade {
				foreach y of numlist 1/4{
				g `t'_y`y'=`t'
	}
	}
	drop grade year masscode
	
save  "$data\peers.dta", replace

	voteruse
	
	*generate vars for where people are in the 4 years after the lottery
	foreach t in year masscode grade {
	foreach y of numlist 1/4{
				g `t'_y`y'=.
	}
	}

*fill in vars for where people are in the 4 years after the lottery
		foreach t in year masscode  {
		foreach n of numlist 4 5 8{
			foreach y of numlist 1/4{
			local n1 = `n'+`y'
			replace `t'_y`y' = `t'`n1' if baselinegrade==`n'
			}
		}
	}
		foreach n of numlist 4 5 8{
			foreach y of numlist 1/4{
			local n1 = `n'+`y'
			replace grade_y`y' = `n1' if baselinegrade==`n'
			}
		}
	
		foreach y of numlist 1/4 { //1/4
			merge m:1 year_y`y' grade_y`y' masscode_y`y' using "$data\peers.dta", nogen keep(1 3) keepusing(baselinepeer*) update
			foreach g of numlist 4 5 8{
			ren baselinepeer_m_`g' baselinepeer_m_`g'_y`y'
			ren baselinepeer_e_`g' baselinepeer_e_`g'_y`y'
			ren baselinepeer_a_`g' baselinepeer_a_`g'_y`y'
			ren baselinepeer_v_`g' baselinepeer_v_`g'_y`y'
				}
			}
foreach y of numlist 1/4{
g baselinepeer_a_y`y'=.
g baselinepeer_m_y`y' =. 
g baselinepeer_e_y`y'=.
g baselinepeer_v_y`y' =. 

}

foreach v in baselinepeer_a baselinepeer_m baselinepeer_e baselinepeer_v {
	foreach y of numlist 1/4{
	foreach g of numlist 4 5 8{
		replace `v'_y`y' =`v'_`g'_y`y' if baselinegrade==`g'
		}
	}
}
drop baselinepeer_a_4_y1-baselinepeer_m_8_y4 baselinepeer*5* baselinepeer*8* masscode_y* grade_y* year_y*

 
foreach g in a e m v {
foreach n of numlist 1/4{
	
global Y baselinepeer_`g'_y`n'
endog

qui g ${Y}_Y0=${Y}*oneminusD

qui ivreg2 ${Y} (D = $Z1 $Z2) $covariates $risksets if  voter_sample==1 , partial($covariates $risksets) robust
preserve
	qui regsave using peergraph, ci pval addlabel(outcome, ${Y}, sample,  `g', year, `n')  append
restore	
qui ivreg2 ${Y}_Y0 (oneminusD = $Z1 $Z2) $covariates $risksets if  voter_sample==1 , partial($covariates $risksets) robust
preserve
	qui regsave using peergraph, ci pval addlabel(outcome, ${Y}, sample,   `g', year, `n')  append
restore
}
}


*graph version
use "$output/peergraph.dta", clear

	drop save r2  N
	g count = _n

reshape wide coef ci_* stderr pval* count, i(outcome year sample ) j( var ) string

g star  = ""
replace star = "*" if pvalD<0.1
replace star = "**" if pvalD<0.05

tostring coefD, generate(te) format( "%9.3fc") force
tostring stderrD, generate(se) format( "%9.3fc") force
g impact = "LATE: " + te + star + " (" + se + ")"
g impact1 = "LATE: " + te + star 
g impact2 = "(" + se + ")"

drop stderr*

foreach v of varlist coefD ci_lowerD ci_upperD {
	replace `v' = `v'+coefoneminusD
}
reshape long coef ci_lower ci_upper count , i(outcome year sample impact ) j(var) string

replace var = "TCM" if var =="D"
replace var = "CCM" if var =="oneminusD"

replace sample = "1" if sample =="a"
replace sample = "2" if sample =="m"
replace sample = "3" if sample =="e"
replace sample = "4" if sample =="v"

destring sample, replace

sort  outcome sample var year

local counter = 2
qui levelsof outcome, local(vars)
		foreach v of local vars{
			global `v'1: di impact1[`counter']
			global `v'2: di impact2[`counter']
			local ++counter
			local ++counter
	}
	

g out=.
	replace out = year+.025 if var=="TCM"
	replace out = year-.025 if var=="CCM"
	
	
	graph twoway scatter coef out if sample==1 & var=="TCM" , mc("${color_3}") msym(O) ///
				 mlabel(coef) mlabc(black) mlabp(1) mlabf(%9.1f) mlabs(small) ///
		|| scatter coef out if sample==1 & var=="CCM" , mc("gray") msym(S) ///
		 mlabel(coef) mlabc(black) mlabp(6) mlabf(%9.1f) mlabs(small) ///
		|| rcap ci_lower ci_upper out if sample==1  &var=="TCM",  lc("${color_3}") lw(medium) ///
		||	line coef out if sample==1 & var=="TCM" ,  lc("${color_3}")  lp(solid) /// 
		|| line coef out if sample==1 & var=="CCM" ,  lc(gray)  lp(dash) ///
			xsc(r(0.65 4.35)) ysc(r(165 171)) yl(165(5)170) ysc(extend) xsc(extend) ///
						xlabel(1 `" "{bf:1}" "$baselinepeer_a_y11" "$baselinepeer_a_y12" "' ///
					 2 `" "{bf:2}" "$baselinepeer_a_y21" "$baselinepeer_a_y22"  "' ///
					 3 `" "{bf:3}"  "$baselinepeer_a_y31" "$baselinepeer_a_y32"  "' ///
					 4 `" "{bf:4}" "$baselinepeer_a_y41" "$baselinepeer_a_y42"  "', labs(small)) ///
				ytitle("Peer Baseline Days of Attendance", size(small))	///
				xtitle("Year after Lottery", size(small))	///
			legend(pos(6) order(1 "Treated Compliers" 2 "Untreated Compliers") size(small) row(1)) ///
			title(B. Attendance ) name(attend, replace) xsize(8.5) ysize(5.5)

			
	graph twoway scatter coef out if sample==2 & var=="TCM" , mc("${color_3}") msym(O) ///
				 mlabel(coef) mlabc(black) mlabp(1) mlabf(%9.2f) mlabs(small) ///
		|| scatter coef out if sample==2 & var=="CCM" , mc("gray") msym(S) ///
		 mlabel(coef) mlabc(black) mlabp(7) mlabf(%9.2f) mlabs(small) ///
		|| rcap ci_lower ci_upper out if sample==2  &var=="TCM",  lc("${color_3}") lw(medium) ///
		||	line coef out if sample==2 & var=="TCM" ,  lc("${color_3}")  lp(solid) /// 
		|| line coef out if sample==2 & var=="CCM" ,  lc(gray)  lp(dash) ///
			xsc(r(0.65 4.35)) ysc(r(-.75 -.25)) yl(-.75(.25) -.25) ysc(extend) xsc(extend) ///
						xlabel(1 `" "{bf:1}" "$baselinepeer_m_y11" "$baselinepeer_m_y12" "' ///
					 2 `" "{bf:2}" "$baselinepeer_m_y21" "$baselinepeer_m_y22"  "' ///
					 3 `" "{bf:3}"  "$baselinepeer_m_y31" "$baselinepeer_m_y32"  "' ///
					 4 `" "{bf:4}" "$baselinepeer_m_y41" "$baselinepeer_m_y42"  "', labs(small)) ///
				ytitle("Peer Baseline Math Score", size(small))	///
				xtitle("Year after Lottery", size(small))	///
			legend(pos(6) order(1 "Treated Compliers" 2 "Untreated Compliers") size(small) row(1)) ///
			title(C. Math ) name(math, replace) xsize(8.5) ysize(5.5)

			
		graph twoway scatter coef out if sample==3 & var=="TCM" , mc("${color_3}") msym(O) ///
				 mlabel(coef) mlabc(black) mlabp(1) mlabf(%9.2f) mlabs(small) ///
		|| scatter coef out if sample==3 & var=="CCM" , mc("gray") msym(S) ///
		 mlabel(coef) mlabc(black) mlabp(7) mlabf(%9.2f) mlabs(small) ///
		|| rcap ci_lower ci_upper out if sample==3  &var=="TCM",  lc("${color_3}") lw(medium) ///
		||	line coef out if sample==3 & var=="TCM" ,  lc("${color_3}")  lp(solid) /// 
		|| line coef out if sample==3 & var=="CCM" ,  lc(gray)  lp(dash) ///
			xsc(r(0.65 4.35)) ysc(r(-.75 -.25)) yl(-.75(.25) -.25) ysc(extend) xsc(extend) ///
						xlabel(1 `" "{bf:1}" "$baselinepeer_e_y11" "$baselinepeer_e_y12" "' ///
					 2 `" "{bf:2}" "$baselinepeer_e_y21" "$baselinepeer_e_y22"  "' ///
					 3 `" "{bf:3}"  "$baselinepeer_e_y31" "$baselinepeer_e_y32"  "' ///
					 4 `" "{bf:4}" "$baselinepeer_e_y41" "$baselinepeer_e_y42"  "', labs(small)) ///
				ytitle("Peer Baseline ELA Score", size(small))	///
				xtitle("Year after Lottery", size(small))	///
			legend(pos(6) order(1 "Treated Compliers" 2 "Untreated Compliers") size(small) row(1)) ///
			title(D. ELA ) name(ela, replace) xsize(8.5) ysize(5.5)
			
		graph twoway scatter coef out if sample==4 & var=="TCM" , mc("${color_3}") msym(O) ///
				 mlabel(coef) mlabc(black) mlabp(1) mlabf(%9.2f) mlabs(small) ///
		|| scatter coef out if sample==4 & var=="CCM" , mc("gray") msym(S) ///
		 mlabel(coef) mlabc(black) mlabp(7) mlabf(%9.2f) mlabs(small) ///
		|| rcap ci_lower ci_upper out if sample==4  &var=="TCM",  lc("${color_3}") lw(medium) ///
		||	line coef out if sample==4 & var=="TCM" ,  lc("${color_3}")  lp(solid) /// 
		|| line coef out if sample==4 & var=="CCM" ,  lc(gray)  lp(dash) ///
			xsc(r(0.65 4.35)) ysc(r(.3 .45)) yl(.3(.05) .45) ysc(extend) xsc(extend) ///
						xlabel(1 `" "{bf:1}" "$baselinepeer_v_y11" "$baselinepeer_v_y12" "' ///
					 2 `" "{bf:2}" "$baselinepeer_v_y21" "$baselinepeer_v_y22"  "' ///
					 3 `" "{bf:3}"  "$baselinepeer_v_y31" "$baselinepeer_v_y32"  "' ///
					 4 `" "{bf:4}" "$baselinepeer_v_y41" "$baselinepeer_v_y42"  "', labs(small)) ///
				ytitle("Predicted Peer Voting", size(small))	///
				xtitle("Year after Lottery", size(small))	///
			legend(pos(6) order(1 "Treated Compliers" 2 "Untreated Compliers") size(small) row(1)) ///
			title(A. Predicted Voting ) name(vote, replace) xsize(8.5) ysize(5.5)
			
			
	grc1leg2 vote attend math ela  , col(2) ysize(11) xsize(8.5) altshrink
	graph export f_peers.pdf, replace
	

}


if $fn_voter == 1{
estimates clear
clear
g save = 1
save main, replace

voteruse


global longvote2 share_gen share_pres second_pos_pres first_pos_pres ever_pprimary ever_primary ever_gen_offcycle ever_general ever_pres ever_voted registered_by_21 registered_by_19 ever_registered  ever_D       

foreach y of varlist $longvote2 yearsbyfirst {
global Y `y'
endog

global lab_${Y} : variable label ${Y}
qui g ${Y}_Y0=${Y}*oneminusD

qui eststo iv_${Y}: ivreg2 ${Y} (D = $Z1 $Z2) $covariates $risksets if  voter_sample==1 , partial($covariates $risksets) robust
preserve
	qui regsave using main, ci pval addlabel(outcome, `y', sample,  all)  append
restore	
qui ivreg2 ${Y}_Y0 (oneminusD = $Z1 $Z2) $covariates $risksets if  voter_sample==1 , partial($covariates $risksets) robust
preserve
	qui regsave using main, ci pval addlabel(outcome, `y', sample,  all)  append
restore
}
voteruse

*graph version

use "$output/main.dta", clear
drop save r2  N
g count = _n

reshape wide coef ci_* stderr pval* count, i(outcome sample) j(var) string

g star  = ""
replace star = "*" if pvalD<0.1
replace star = "**" if pvalD<0.05

tostring coefD, generate(te) format( "%9.3fc") force
tostring stderrD, generate(se) format( "%9.3fc") force
g impact = "LATE: " + te + star + " (" + se + ")"
g impact1 = "LATE: " + te + star 
g impact2 = "(" + se + ")"

drop stderr*

foreach v of varlist coefD ci_lowerD ci_upperD {
	replace `v' = `v'+coefoneminusD
}
reshape long coef ci_lower ci_upper count , i(outcome sample impact) j(var) string

replace var = "TCM" if var =="D"
replace var = "CCM" if var =="oneminusD"

replace sample = "1" if sample =="all"
destring sample, replace

g sample_1 = sample-.175
g sample_2 = sample+.175

sort  outcome sample     var 

local counter = 2
qui levelsof outcome, local(vars)
		foreach g of local vars{
		foreach sample in all  {
			global `g'_`sample': di impact1[`counter']
			global `g'_`sample'2: di impact2[`counter']
			local ++counter
			local ++counter
		}
	}
	
sort sample count var

preserve
	keep if (outcome=="ever_registered" |outcome=="registered_by_19" | outcome=="ever_D") & sample == 1
	replace outcome = "1" if outcome=="ever_registered"
	replace outcome = "2" if outcome=="registered_by_19"
	replace outcome = "3" if outcome=="ever_D"
	destring outcome, replace
	sort outcome var
	drop sample*
	g sample = outcome - .175 if var=="CCM"
	replace sample = outcome + .175 if var=="TCM"

	twoway bar coef sample if var=="CCM", barw(.34) fc("${color_c}%70")  lc("${color_c}") lw(medthick) ///
			|| bar coef sample if var=="TCM", barw(.34) fc("${color_t}%70")  lc("${color_t}") lw(medthick) ///
			|| rcap ci_lower ci_upper sample if var=="CCM",  lc("${color_c}") lw(medium) ///
			|| rcap ci_lower ci_upper sample if var=="TCM",  lc("${color_t}") lw(medium) , ///
			|| scatter coef sample if var=="CCM", ms(i) mlabel(coef) mlabc(black) mlabp(10) mlabf(%9.2f) mlabs(small)  ///		
			|| scatter coef sample if var=="TCM", ms(i) mlabel(coef) mlabc(black) mlabp(10) mlabf(%9.2f) mlabs(small)  ///		
			yscale(r(0 .9)) ysc(extend) xsc(extend) ///
			yl(0(.2).8, labs(medsmall)) ytitle("Fraction", size(medium)) ///
			xlabel(1 `" "{bf:Ever Registered}" "$ever_registered_all" "$ever_registered_all2" "' ///
					 2 `"  "{bf:Registered by 19 }" "$registered_by_19_all" "$registered_by_19_all2"  "' ///
					 3 `"  "{bf:Ever Democrat}"  "$ever_D_all" "$ever_D_all2" "', labs(medium)) ///
			title("`lab'", size(medlarge)) xtitle("") title(A. Registration) ///
			legend(pos(6) row(1) order(1 "Untreated Compliers" 2 "Treated Compliers") size(medium)) ///
			name(key_reg, replace)
restore


preserve
	keep if (outcome=="ever_pres" |outcome=="share_pres" | outcome=="first_pos_pres") & sample == 1
	replace outcome = "1" if outcome=="ever_pres"
	replace outcome = "2" if outcome=="share_pres"
	replace outcome = "3" if outcome=="first_pos_pres"
	destring outcome, replace
	sort outcome var
	drop sample*
	g sample = outcome - .175 if var=="CCM"
	replace sample = outcome + .175 if var=="TCM"

	twoway bar coef sample if var=="CCM", barw(.34) fc("${color_c}%70")  lc("${color_c}") lw(medthick) ///
			|| bar coef sample if var=="TCM", barw(.34) fc("${color_t}%70")  lc("${color_t}") lw(medthick) ///
			|| rcap ci_lower ci_upper sample if var=="CCM",  lc("${color_c}") lw(medium) ///
			|| rcap ci_lower ci_upper sample if var=="TCM",  lc("${color_t}") lw(medium) , ///
			|| scatter coef sample if var=="CCM", ms(i) mlabel(coef) mlabc(black) mlabp(10) mlabf(%9.2f) mlabs(small)  ///		
			|| scatter coef sample if var=="TCM", ms(i) mlabel(coef) mlabc(black) mlabp(10) mlabf(%9.2f) mlabs(small)  ///		
			yscale(r(0 .7)) ysc(extend) xsc(extend) ///
			yl(0(.2).7, labs(medsmall)) ytitle("Fraction", size(medium)) ///
			xlabel(1 `" "{bf:Ever Presidential}" "$ever_pres_all" "$ever_pres_all2" "' ///
					 2 `"  "{bf:Share Presidential }" "$share_pres_all"  "$share_pres_all2" "' ///
					 3 `"  "{bf:First Possible}"  "$first_pos_pres_all" "$first_pos_pres_all2"  "', labs(medium)) ///
			title("`lab'", size(medlarge)) xtitle("")  title(B. Presidential Elections)  ///
			legend(pos(6) row(1) order(1 "Untreated Compliers" 2 "Treated Compliers") size(medium)) ///
			name(key_pres, replace)
restore


 grc1leg2 key_reg  key_pres , row(2) ysize(11) xsize(8.5) altshrink labsize(small)
				graph export f_voting_vert.pdf, replace 
 grc1leg2 key_reg  key_pres , row(1) xsize(11) ysize(4.25) altshrink labsize(small)
				graph export f_voting_horiz.pdf, replace 

}	
if $tn_voter == 1{
estimates clear
voteruse

global vote1 ever_registered  registered_by_19 ever_D ever_pres share_pres first_pos_pres 
global vote2  /*ever_voted*/ ever_general share_gen first_pos_gen first_pos_gen_o ever_pprimary ever_primary /* ever_gen_offcycle*/

foreach y of varlist $vote1  {
global Y `y' 

	voterreg2 
	
	qui ivreg2 ${Y} (D = $Z1 $Z2) $covariates $risksets if  voter_sample==1 ///
		, partial($covariates $risksets) robust rf saverfp(rf_) /*cluster($clustervar)*/
			estimates restore rf_$Y
		qui su ${Y} if $Z1==0&$Z2==0
		estadd scalar m=r(mean)	
	
}

	file open  t	using tn_voter.tex, replace write
	file write t	"\begin{table}[htbp!] \centering" _n "\def\sym#1{\ifmmode^{#1}\else\(^{#1}\)\fi}" _n ///
					"\caption{The Impact of Charter School Offers and Attendance on Voting  }"_n "\label{tn_voter}" _n  "\small" _n ///
					"\begin{tabular*}{1\textwidth}{@{\extracolsep{\fill}}l*{6}{c}}" _n "\midrule" _n ///
					"&\multicolumn{3}{c}{Registration}&\multicolumn{3}{c}{Presidential Elections}\\" _n ///
					"\cline{2-4} \cline{5-7}  \\" _n ///
					"&		&Registered 	&Ever & 		& 		& First\\" _n ///
					"&Ever& by	19th		& Registered &Ever	&Share 	& Possible \\" _n ///
					"&Registered&  Birthday&  Democrat &Presidential	& Presidential & Presidential \\" _n ///
					"&(1)&(2)&(3)&(4)&(5)&(6)\\" _n ///
					"\midrule"  _n  "\textit{Reduced Form}\\" _n
file close t

	esttab rf_* 	using tn_voter.tex, k($Z1 $Z2) coef($Z1 "Initial Offer" $Z2 "Waitlist Offer" ) s(m, l( "\hspace{.25cm} Non-offered mean" ) f(3 ) lay( @ `""')) $opts  	
	file open  t	using tn_voter.tex, append write
file write t "\textit{Second Stage}\\" _n
file close t 
	esttab iv_* 	using tn_voter.tex, k($D) coef($D "2SLS ") s(ccm N, l( "\hspace{.25cm} CCM" ""  "\hspace{.25cm} \textit{N} " "") f(3 %9.0fc) lay( @ `""'  @ `""')) $opts  	
	
	*SECOND BATCH
estimates clear
foreach y of varlist $vote2  {
global Y `y' 
	voterreg2 
	
		
	qui ivreg2 ${Y} (D = $Z1 $Z2) $covariates $risksets if  voter_sample==1 ///
		, partial($covariates $risksets) robust rf saverfp(rf_) /*cluster($clustervar)*/
			estimates restore rf_$Y
		qui su ${Y} if $Z1==0&$Z2==0
		estadd scalar m=r(mean)	

}

	file open  t	using tn_voter.tex, append write
	file write t	"&\multicolumn{4}{c}{General Elections}&\multicolumn{2}{c}{Other Elections}\\" _n ///
					"\cline{2-5} \cline{6-7}  \\" _n ///
					"	& 	Ever		&	Share	&First Pos.	& First Pos.	 & 	Ever	& Ever		\\" _n ///
					"	&General		& 	General		& General & Off-Cycle&	Presidential &Other 	\\" _n ///
					"&Election	& Elections &   Election  &General	&Primary	& Primary  \\" _n ///
					"&(7)&(8)&(9)&(10)&(11)&(12)\\" _n ///
					"\midrule"  _n "\textit{Reduced Form}\\" _n
file close t

	esttab rf_* 	using tn_voter.tex, k($Z1 $Z2) coef($Z1 "Initial Offer" $Z2 "Waitlist Offer" ) s(m, l( "\hspace{.25cm} Non-offered mean" ) f(3 ) lay( @ `""')) $opts  
	file open  t	using tn_voter.tex, append write
file write t "\textit{Second Stage}\\" _n
file close t 
	esttab iv_* 	using tn_voter.tex, k($D) coef($D "2SLS ") s(ccm N, l( "\hspace{.25cm} CCM" ""  "\hspace{.25cm} \textit{N} " "") f(3 %9.0fc) lay( @ `""'  @ )) $opts  
 		
	file open  t 	using tn_voter.tex, append write
	file write t 	"\midrule" _n "\end{tabular*}" _n ///
					"\begin{tabular*}{1\textwidth}{p{6.3in}}" _n ///
					"\footnotesize Notes:  " ///
					"$note_rf" "$note_iv" "$note_z" "$note_ccm" "$note_controls" "$note_sample" ///
					"Voting outcomes come from the Massachusetts voter file, supplemented with voting records from nearby states. The ``Off-Cycle'' elections are general elections in non-presidential years.  $note_stars" ///
					"\end{tabular*}" _n "\end{table}" _n 
	file close t
		


	
}
if $fn_voter_overtime == 1{
estimates clear
clear
g save = 1
save time, replace

global longvote2 third_pos_pres second_pos_pres first_pos_pres     

*all 
voteruse
foreach y of varlist $longvote2  {
global Y `y'
endog

global lab_${Y} : variable label ${Y}
qui g ${Y}_Y0=${Y}*oneminusD

qui eststo iv_${Y}: ivreg2 ${Y} (D = $Z1 $Z2) $covariates $risksets if  voter_sample==1 , partial($covariates $risksets) robust
preserve
	qui regsave using time, ci pval addlabel(outcome, `y', sample,  all)  append
restore	
qui ivreg2 ${Y}_Y0 (oneminusD = $Z1 $Z2) $covariates $risksets if  voter_sample==1 , partial($covariates $risksets) robust
preserve
	qui regsave using time, ci pval addlabel(outcome, `y', sample,  all)  append
restore
}

*balanced sample* 
voteruse
keep if third_pos_pres!=.
foreach y of varlist $longvote2  {
global Y `y'
endog

global lab_${Y} : variable label ${Y}
qui g ${Y}_Y0=${Y}*oneminusD

qui eststo iv_${Y}: ivreg2 ${Y} (D = $Z1 $Z2) $covariates $risksets if  voter_sample==1 , partial($covariates $risksets) robust
preserve
	qui regsave using time, ci pval addlabel(outcome, `y', sample,  balanced)  append
restore	
qui ivreg2 ${Y}_Y0 (oneminusD = $Z1 $Z2) $covariates $risksets if  voter_sample==1 , partial($covariates $risksets) robust
preserve
	qui regsave using time, ci pval addlabel(outcome, `y', sample,  balanced)  append
restore
}

*all omitting out of state college goers
voteruse
keep if college_OOS_private !=1& college_OOS_public!=1
foreach y of varlist $longvote2  {
global Y `y'
endog

global lab_${Y} : variable label ${Y}
qui g ${Y}_Y0=${Y}*oneminusD

qui eststo iv_${Y}: ivreg2 ${Y} (D = $Z1 $Z2) $covariates $risksets if  voter_sample==1 , partial($covariates $risksets) robust
preserve
	qui regsave using time, ci pval addlabel(outcome, `y', sample,  noOOSall)  append
restore	
qui ivreg2 ${Y}_Y0 (oneminusD = $Z1 $Z2) $covariates $risksets if  voter_sample==1 , partial($covariates $risksets) robust
preserve
	qui regsave using time, ci pval addlabel(outcome, `y', sample,  noOOSall)  append
restore
}

*balanced sample omitting out of state college goers 
voteruse
keep if third_pos_pres!=. & college_OOS_private !=1& college_OOS_public!=1
foreach y of varlist $longvote2  {
global Y `y'
endog

global lab_${Y} : variable label ${Y}
qui g ${Y}_Y0=${Y}*oneminusD

qui eststo iv_${Y}: ivreg2 ${Y} (D = $Z1 $Z2) $covariates $risksets if  voter_sample==1 , partial($covariates $risksets) robust
preserve
	qui regsave using time, ci pval addlabel(outcome, `y', sample,  noOOSbalanced)  append
restore	
qui ivreg2 ${Y}_Y0 (oneminusD = $Z1 $Z2) $covariates $risksets if  voter_sample==1 , partial($covariates $risksets) robust
preserve
	qui regsave using time, ci pval addlabel(outcome, `y', sample,  noOOSbalanced)  append
restore
}


*graph version
use "$output/time.dta", clear

	drop save r2  N
	g count = _n

reshape wide coef ci_* stderr pval* count, i(outcome sample ) j(var ) string

g star  = ""
replace star = "*" if pvalD<0.1
replace star = "**" if pvalD<0.05

tostring coefD, generate(te) format( "%9.3fc") force
tostring stderrD, generate(se) format( "%9.3fc") force
g impact = "LATE: " + te + star + " (" + se + ")"
g impact1 = "LATE: " + te + star 
g impact2 = "(" + se + ")"

drop stderr*

foreach v of varlist coefD ci_lowerD ci_upperD {
	replace `v' = `v'+coefoneminusD
}
reshape long coef ci_lower ci_upper count , i(outcome sample impact ) j(var) string

replace var = "TCM" if var =="D"
replace var = "CCM" if var =="oneminusD"

replace sample = "1" if sample =="all"
replace sample = "2" if sample =="balanced"
replace sample = "3" if sample =="noOOSall"
replace sample = "4" if sample =="noOOSbalanced"

destring sample, replace

sort  outcome sample var 

local counter = 2
qui levelsof outcome, local(vars)
		foreach v of local vars{
		foreach sample in all balanced noOOSall noOOSbalanced {
			global `v'_`sample': di impact[`counter']
			local ++counter
			local ++counter
		}
	}
	
sort sample count var

	encode outcome, gen(out)
	replace out = out+.025 if var=="TCM"
	replace out = out-.025 if var=="CCM"
	
save "$output/time_all.dta", replace


use "$output/time_all.dta", clear

	graph twoway scatter coef out if sample==1 & var=="TCM" , mc("${color_3}") msym(O) ///
				 mlabel(coef) mlabc(black) mlabp(1) mlabf(%9.2f) mlabs(small) ///
		|| scatter coef out if sample==1 & var=="CCM" , mc("gray") msym(S) ///
		 mlabel(coef) mlabc(black) mlabp(7) mlabf(%9.2f) mlabs(small) ///
		|| rcap ci_lower ci_upper out if sample==1  &var=="TCM",  lc("${color_3}") lw(medium) ///
		|| rcap ci_lower ci_upper out if sample==1  &var=="CCM",  lc(gray) lw(medium) /// 
		||	line coef out if sample==1 & var=="TCM" ,  lc("${color_3}")  lp(solid) /// 
				|| line coef out if sample==1 & var=="CCM" ,  lc(gray)  lp(dash) ///
		xsc(r(0.65 3.35)) ysc(r(0 .65)) yl(0(.2).6) ysc(extend) xsc(extend) ///
				xlabel(1 `" "{bf:First Possible}" "$first_pos_pres_all" "' ///
					 2 `"  "{bf:Second Possible}"  "$second_pos_pres_all" "' ///
					 3 `"  "{bf:Third Possible}" "$third_pos_pres_all" "', labs(small)) ///
			ytitle("Fraction", size(small))	xtitle("")	///
			legend(pos(6) order(1 "Treated Compliers" 2 "Untreated Compliers") size(small) row(1)) ///

			
	graph twoway scatter coef out if sample==2 & var=="TCM" , mc("${color_3}") msym(O) ///
				 mlabel(coef) mlabc(black) mlabp(1) mlabf(%9.2f) mlabs(small) ///
		|| scatter coef out if sample==2 & var=="CCM" , mc("gray") msym(S) ///
		 mlabel(coef) mlabc(black) mlabp(7) mlabf(%9.2f) mlabs(small) ///
		|| rcap ci_lower ci_upper out if sample==2  &var=="TCM",  lc("${color_3}") lw(medium) ///
		|| rcap ci_lower ci_upper out if sample==2  &var=="CCM",  lc(gray) lw(medium) /// 
		||	line coef out if sample==2 & var=="TCM" ,  lc("${color_3}")  lp(solid) /// 
		|| line coef out if sample==2 & var=="CCM" ,  lc(gray)  lp(dash) ///
			xsc(r(0.65 3.35)) ysc(r(0 .65)) yl(0(.2).6) ysc(extend) xsc(extend) ///
				xlabel(1 `" "{bf:First Possible}" "$first_pos_pres_balanced" "' ///
					 2 `"  "{bf:Second Possible}"  "$second_pos_pres_balanced" "' ///
					 3 `"  "{bf:Third Possible}" "$third_pos_pres_balanced" "', labs(small)) ///
			ytitle("Fraction", size(small))	xtitle("")	///
			legend(pos(6) order(1 "Treated Compliers" 2 "Untreated Compliers") size(small) row(1)) ///
			title(B. Balanced Panel) name(balanced, replace) xsize(8.5) ysize(5.5)
			
	graph twoway scatter coef out if sample==3 & var=="TCM" , mc("${color_3}") msym(O) ///
				 mlabel(coef) mlabc(black) mlabp(1) mlabf(%9.2f) mlabs(small) ///
		|| scatter coef out if sample==3 & var=="CCM" , mc("gray") msym(S) ///
		 mlabel(coef) mlabc(black) mlabp(7) mlabf(%9.2f) mlabs(small) ///
		|| rcap ci_lower ci_upper out if sample==3  &var=="TCM",  lc("${color_3}") lw(medium) ///
		|| rcap ci_lower ci_upper out if sample==3  &var=="CCM",  lc(gray) lw(medium) /// 
		||	line coef out if sample==3 & var=="TCM" ,  lc("${color_3}")  lp(solid) /// 
		|| line coef out if sample==3 & var=="CCM" ,  lc(gray)  lp(dash) ///
			xsc(r(0.65 3.35)) ysc(r(0 .65)) yl(0(.2).6) ysc(extend) xsc(extend) ///
				xlabel(1 `" "{bf:First Possible}" "$first_pos_pres_noOOSall" "' ///
					 2 `"  "{bf:Second Possible}"  "$second_pos_pres_noOOSall" "' ///
					 3 `"  "{bf:Third Possible}" "$third_pos_pres_noOOSall" "', labs(small)) ///
			ytitle("Fraction", size(small))	xtitle("")	///
			legend(pos(6) order(1 "Treated Compliers" 2 "Untreated Compliers") size(small) row(1)) ///
			title("C. All Data, No Out-of-State") name(noOOSall, replace) xsize(8.5) ysize(5.5)
			
	graph twoway scatter coef out if sample==4 & var=="TCM" , mc("${color_3}") msym(O) ///
				 mlabel(coef) mlabc(black) mlabp(1) mlabf(%9.2f) mlabs(small) ///
		|| scatter coef out if sample==4 & var=="CCM" , mc("gray") msym(S) ///
		 mlabel(coef) mlabc(black) mlabp(7) mlabf(%9.2f) mlabs(small) ///
		|| rcap ci_lower ci_upper out if sample==4  &var=="TCM",  lc("${color_3}") lw(medium) ///
		||	line coef out if sample==4 & var=="TCM" ,  lc("${color_3}")  lp(solid) /// 
		|| line coef out if sample==4 & var=="CCM" ,  lc(gray)  lp(dash) ///
			xsc(r(0.65 3.35)) ysc(r(0 .65)) yl(0(.2).6) ysc(extend) xsc(extend) ///
				xlabel(1 `" "{bf:First Possible}" "$first_pos_pres_noOOSbalanced" "' ///
					 2 `"  "{bf:Second Possible}"  "$second_pos_pres_noOOSbalanced" "' ///
					 3 `"  "{bf:Third Possible}" "$third_pos_pres_noOOSbalanced" "', labs(small)) ///
			ytitle("Fraction", size(small))	xtitle("")	///
			legend(pos(6) order(1 "Treated Compliers" 2 "Untreated Compliers") size(small) row(1)) ///
			title("D. Balanced Panel, No Out-of-State") name(noOOSbalanced, replace) xsize(8.5) ysize(5.5)
			
 grc1leg2 all  balanced noOOSall  noOOSbalanced , row(2) ysize(11) xsize(8.5) altshrink labsize(small)
				graph export f_overtime.pdf, replace 
				
							
}
*combined graph
if $fn_combined==1{
estimates clear
clear
g save = 1
save main2, replace

voteruse


global longvote2 third_pos_pres second_pos_pres first_pos_pres share_pres ever_pres   registered_by_19 ever_registered  ever_D       

foreach y of varlist $longvote2  {
global Y `y'
endog

global lab_${Y} : variable label ${Y}
qui g ${Y}_Y0=${Y}*oneminusD

qui eststo iv_${Y}: ivreg2 ${Y} (D = $Z1 $Z2) $covariates $risksets if  voter_sample==1 , partial($covariates $risksets) robust
preserve
	qui regsave using main2, ci pval addlabel(outcome, `y', sample,  all)  append
restore	
qui ivreg2 ${Y}_Y0 (oneminusD = $Z1 $Z2) $covariates $risksets if  voter_sample==1 , partial($covariates $risksets) robust
preserve
	qui regsave using main2, ci pval addlabel(outcome, `y', sample,  all)  append
restore
}


*graph version

use "$output/main2.dta", clear
drop save r2  N
g count = _n

reshape wide coef ci_* stderr pval* count, i(outcome sample) j(var) string

g star  = ""
replace star = "*" if pvalD<0.1
replace star = "**" if pvalD<0.05

tostring coefD, generate(te) format( "%9.3fc") force
tostring stderrD, generate(se) format( "%9.3fc") force
g impact = "LATE: " + te + star + " (" + se + ")"
g impact1 = "LATE: " + te + star 
g impact2 = "(" + se + ")"

drop stderr*

foreach v of varlist coefD ci_lowerD ci_upperD {
	replace `v' = `v'+coefoneminusD
}
reshape long coef ci_lower ci_upper count , i(outcome sample impact) j(var) string

replace var = "TCM" if var =="D"
replace var = "CCM" if var =="oneminusD"

replace sample = "1" if sample =="all"
destring sample, replace

g sample_1 = sample-.175
g sample_2 = sample+.175

sort  outcome sample     var 

local counter = 2
qui levelsof outcome, local(vars)
		foreach g of local vars{
		foreach sample in all  {
			global `g'_`sample': di impact1[`counter']
			global `g'_`sample'2: di impact2[`counter']
			local ++counter
			local ++counter
		}
	}
	
sort sample count var

preserve
	keep if (outcome=="ever_registered" |outcome=="registered_by_19" | outcome=="ever_D") & sample == 1
	replace outcome = "1" if outcome=="ever_registered"
	replace outcome = "2" if outcome=="registered_by_19"
	replace outcome = "3" if outcome=="ever_D"
	destring outcome, replace
	sort outcome var
	drop sample*
	g sample = outcome - .175 if var=="CCM"
	replace sample = outcome + .175 if var=="TCM"

	twoway bar coef sample if var=="CCM", barw(.34) fc("${color_c}%70")  lc("${color_c}") lw(medthick) ///
			|| bar coef sample if var=="TCM", barw(.34) fc("${color_t}%70")  lc("${color_t}") lw(medthick) ///
			|| rcap ci_lower ci_upper sample if var=="CCM",  lc("${color_c}") lw(medium) ///
			|| rcap ci_lower ci_upper sample if var=="TCM",  lc("${color_t}") lw(medium) , ///
			|| scatter coef sample if var=="CCM", ms(i) mlabel(coef) mlabc(black) mlabp(10) mlabf(%9.2f) mlabs(small)  ///		
			|| scatter coef sample if var=="TCM", ms(i) mlabel(coef) mlabc(black) mlabp(10) mlabf(%9.2f) mlabs(small)  ///		
			yscale(r(0 .9)) ysc(extend) xsc(extend) ///
			yl(0(.2).8, labs(medsmall)) ytitle("Fraction", size(medium)) ///
			xlabel(1 `" "{bf:Ever Registered}" "$ever_registered_all" "$ever_registered_all2" "' ///
					 2 `"  "{bf:Registered by 19 }" "$registered_by_19_all" "$registered_by_19_all2"  "' ///
					 3 `"  "{bf:Ever Democrat}"  "$ever_D_all" "$ever_D_all2" "', labs(medium)) ///
			title("`lab'", size(medlarge)) xtitle("") title(A. Registration) ///
			legend(pos(6) row(1) order(1 "Untreated Compliers" 2 "Treated Compliers") size(medium)) ///
			name(key_reg, replace)
restore


preserve
	keep if (outcome=="ever_pres" |outcome=="share_pres" | outcome=="first_pos_pres") & sample == 1
	replace outcome = "1" if outcome=="ever_pres"
	replace outcome = "2" if outcome=="share_pres"
	replace outcome = "3" if outcome=="first_pos_pres"
	destring outcome, replace
	sort outcome var
	drop sample*
	g sample = outcome - .175 if var=="CCM"
	replace sample = outcome + .175 if var=="TCM"

	twoway bar coef sample if var=="CCM", barw(.34) fc("${color_c}%70")  lc("${color_c}") lw(medthick) ///
			|| bar coef sample if var=="TCM", barw(.34) fc("${color_t}%70")  lc("${color_t}") lw(medthick) ///
			|| rcap ci_lower ci_upper sample if var=="CCM",  lc("${color_c}") lw(medium) ///
			|| rcap ci_lower ci_upper sample if var=="TCM",  lc("${color_t}") lw(medium) , ///
			|| scatter coef sample if var=="CCM", ms(i) mlabel(coef) mlabc(black) mlabp(10) mlabf(%9.2f) mlabs(small)  ///		
			|| scatter coef sample if var=="TCM", ms(i) mlabel(coef) mlabc(black) mlabp(10) mlabf(%9.2f) mlabs(small)  ///		
			yscale(r(0 .7)) ysc(extend) xsc(extend) ///
			yl(0(.2).7, labs(medsmall)) ytitle("Fraction", size(medium)) ///
			xlabel(1 `" "{bf:Ever Presidential}" "$ever_pres_all" "$ever_pres_all2" "' ///
					 2 `"  "{bf:Share Presidential }" "$share_pres_all"  "$share_pres_all2" "' ///
					 3 `"  "{bf:First Possible}"  "$first_pos_pres_all" "$first_pos_pres_all2"  "', labs(medium)) ///
			title("`lab'", size(medlarge)) xtitle("")  title(B. Presidential Elections)  ///
			legend(pos(6) row(1) order(1 "Untreated Compliers" 2 "Treated Compliers") size(medium)) ///
			name(key_pres, replace)
restore

preserve
	keep if (outcome=="first_pos_pres" |outcome=="second_pos_pres" | outcome=="third_pos_pres") & sample == 1
	replace outcome = "1" if outcome=="first_pos_pres"
	replace outcome = "2" if outcome=="second_pos_pres"
	replace outcome = "3" if outcome=="third_pos_pres"
	destring outcome, replace
	sort outcome var
	drop sample*
	g sample = outcome - .175 if var=="CCM"
	replace sample = outcome + .175 if var=="TCM"

	twoway bar coef sample if var=="CCM", barw(.34) fc("${color_c}%70")  lc("${color_c}") lw(medthick) ///
			|| bar coef sample if var=="TCM", barw(.34) fc("${color_t}%70")  lc("${color_t}") lw(medthick) ///
			|| rcap ci_lower ci_upper sample if var=="CCM",  lc("${color_c}") lw(medium) ///
			|| rcap ci_lower ci_upper sample if var=="TCM",  lc("${color_t}") lw(medium) , ///
			|| scatter coef sample if var=="CCM", ms(i) mlabel(coef) mlabc(black) mlabp(10) mlabf(%9.2f) mlabs(small)  ///		
			|| scatter coef sample if var=="TCM", ms(i) mlabel(coef) mlabc(black) mlabp(10) mlabf(%9.2f) mlabs(small)  ///		
			yscale(r(0 .7)) ysc(extend) xsc(extend) ///
			yl(0(.2).7, labs(medsmall)) ytitle("Fraction", size(medium)) ///
			xlabel(1 `" "{bf:First Possible}" "$first_pos_pres_all" "$first_pos_pres_all2" "' ///
					 2 `"  "{bf:Second Possible }" "$second_pos_pres_all"  "$second_pos_pres_all2" "' ///
					 3 `"  "{bf:Third Possible}"  "$third_pos_pres_all" "$third_pos_pres_all2"  "', labs(medium)) ///
			title("`lab'", size(medlarge)) xtitle("")  title(C. Presidential Elections Over Time)  ///
			legend(pos(6) row(1) order(1 "Untreated Compliers" 2 "Treated Compliers") size(medium)) ///
			name(overtime, replace)
restore
		
		graph combine key_reg key_pres , row(1) name(combo, replace)   iscale(.5) 
		graph combine overtime, imargin(50 50 0 0)  iscale(.5) row(1) name(overtime2, replace)
		grc1leg2 combo  overtime2, row(2) ysize(8.5) xsize(8.5)  labsize(small) 
				graph export f_voting.pdf, replace 
	

}
if $tn_voter_close == 1{

*for figure later
estimates clear
clear
g save = 1
save close_first_pos_pres, replace
save close_yearsbyfirst, replace

estimates clear
	voteruse
	

	

foreach  n  in 8nov2016  6nov2012  4nov2008   {
	gen dif_`n'=(turn18 - td(`n'))	 
	}
g dif = dif_4nov2008 if proj_year<=2009& atleast18_4nov2008==1
replace dif = dif_4nov2008 if proj_year<=2008
replace dif = dif_6nov2012 if proj_year<=2013 & atleast18_6nov2012==1 & dif ==.
replace dif = dif_6nov2012 if proj_year<=2012 & dif ==.
replace dif = dif_8nov2016 if proj_year<=2017 & atleast18_8nov2016==1 & dif ==.
replace dif = dif_8nov2016 if proj_year<=2016 & dif ==.

g close =abs(dif)<730 // less than 2 years away

g close1 =abs(dif)<=100 // in high school
g close2 =abs(dif)>100 & abs(dif)<=365 
g close3 =abs(dif)>365 & abs(dif)<=730 
g close4 =abs(dif)>730 & abs(dif)<=1095 
g close5 =abs(dif)>1095 

 
egen group = group(lottogroupYR_boston close)
qui tab group, gen(gb_)
drop group

g notclose =close==0

foreach v of varlist $covariates {
	g byte g1_`v'=`v'*close
	g byte g2_`v'=`v'*notclose
}

foreach v of varlist $Z1 $Z2 D_by12 D {
	g byte `v'_close=`v'*close
	g byte `v'_notclose=`v'*notclose
}


global outcomes $shortvote  yearsbyfirst yearsever
foreach y of varlist $outcomes  {
g a`y' = `y' 
g c`y' = `y' if close==1
    g n`y' = `y' if notclose==1

global Y a`y'
	voterreg2 
	
global Y c`y'
	voterreg2 

global Y n`y'
	voterreg2 
	
	preserve
global Y `y'

 *covariates and risk sets adjusted by  category 
 qui ivreg2 ${Y} (D_close D_notclose= ${Z1}_close ${Z1}_notclose ${Z2}_close ${Z2}_notclose)  gb_* g1_* g2_*  if  voter_sample==1 , partial(gb_* g1_* g2_* ) robust
 qui test D_close = D_notclose
	global p_${Y} = string(r(p),  "%9.3f")
	di in yellow "p-value for ${Y}: ${p_${Y}}"

restore
}

file open  t	using tn_voter_close.tex, replace write
	file write t	"\begin{table}[htbp!] \centering" _n "\def\sym#1{\ifmmode^{#1}\else\(^{#1}\)\fi}" _n ///
					"\caption{The Impact of Charter School Attendance on Voting, by Age at First Presidential }" _n "\label{tn_voter_close}" _n "\small" _n ///
					"\begin{tabular*}{1\textwidth}{@{\extracolsep{\fill}}l*{5}{c}}" _n "\midrule" _n ///
					"&Ever&Share& Voted in First&Year of Ed by&Years of Ed  \\" _n ///
					"&Registered& Presidential &Possible Pres. &by 1st Pres.&Ever \\" _n ///
					"&(1)&(2)&(3)&(4)&(5)\\" _n ///
					"\midrule"  _n
					
					
file close t
*	esttab iv_a* 	using tn_voter_close.tex, k($D) coef($D "All ") 			s(ccm N, l( "\hspace{.25cm} CCM"   "\hspace{.25cm} \textit{N}" "" ) f(3 %9.0fc) lay(@  @ `""' )) $opts  
	esttab iv_c* 	using tn_voter_close.tex, k($D) coef($D "Turn 18 Close to Pres. Election ") 			s(ccm N, l( "\hspace{.25cm} CCM"   "\hspace{.25cm} \textit{N}" "" ) f(3 %9.0fc) lay(@  @ `""' )) $opts  
	esttab iv_n* 	using tn_voter_close.tex, k($D) coef($D "Turn 18 Farther from Pres. Election") 			s(ccm N, l( "\hspace{.25cm} CCM"   "\hspace{.25cm} \textit{N}" "" ) f(3 %9.0fc) lay(@  @ `""' )) $opts    
	
file open  t 	using tn_voter_close.tex, append write
	file write t 		"\textit{p}-value  & ${p_ever_registered }& ${p_share_pres }&${p_first_pos_pres}&${p_yearsbyfirst }&${p_yearsever}\\" _n 
	file write t 	"\midrule" _n "\end{tabular*}" _n ///
					"\begin{tabular*}{1\textwidth}{p{6.3in}}" _n ///
					"\footnotesize Notes:  " ///
					"$note_iv" "$note_z" "$note_ccm" "$note_controls" "$note_sample"  ///
					"Close to presidential election is defined as students who turn 18 within two years prior to their first possible presidential vote. " ///
					"Farther from presidential election is all other students. " ///
					"The \textit{p}-value from a test of equality of the close to and farther from coefficients is listed in the final row of the table.	" "$note_stars" ///
					"\end{tabular*}" _n "\end{table}" _n 
	file close t	
	
	*figure version
		g oneminusDc = 1-D_close
	g oneminusDn = 1-D_notclose
foreach v in first_pos_pres	yearsbyfirst {
	
cap drop *Y0

	global Y `v'
global lab_${Y} : variable label ${Y}
qui g ${Y}c_Y0=${Y}*oneminusDc
qui g ${Y}n_Y0=${Y}*oneminusDn

 eststo iv_${Y}: ivreg2 ${Y} (D_close D_notclose= ${Z1}_close ${Z1}_notclose ${Z2}_close ${Z2}_notclose) ///
				 gb_* g1_* g2_*  if  voter_sample==1 ///
		, partial( gb_* g1_* g2_* ) robust 

test D_close D_notclose
local p = r(p)	
			qui estadd scalar p=`p'
	global p_${Y} = string(r(p),  "%9.3f")
	di in yellow "p-value for ${Y}: ${p_${Y}}"
preserve
	qui regsave using close_`v', ci pval  addlabel(outcome, `y', pvalcn,  ${p_${Y}})  append
restore			
 qui  ivreg2 ${Y}c_Y0 (oneminusDc oneminusDn =  ///
		${Z1}_close ${Z1}_notclose ${Z2}_close ${Z2}_notclose) ///
				 gb_* g1_* g2_* if  voter_sample==1 ///
		, partial( gb_* g1_* g2_*) robust 	
preserve
	qui regsave using close_`v', ci pval addlabel(outcome, `y', pvalcn,  ${p_${Y}})  append
restore				
  qui ivreg2 ${Y}n_Y0 (oneminusDc oneminusDn =  ///
		${Z1}_close ${Z1}_notclose ${Z2}_close ${Z2}_notclose) ///
	 gb_* g1_* g2_*  if  voter_sample==1 ///
		, partial( gb_* g1_* g2_* ) robust 
preserve
	qui regsave using close_`v', ci pval addlabel(outcome, `y', pvalcn,  ${p_${Y}})  append
restore				

preserve
 
use main.dta, clear
keep if sample == "all" & (outcome=="`v'")
append using close_`v'.dta
drop outcome  N  r2
drop if coef<= 0.02 &(var=="oneminusDc"|var=="oneminusDn" ) //these are the extra CCMs from the two endog model 
replace sample = "close" if var == "oneminusDc"|var=="D_close"
replace sample = "not" if var == "oneminusDn"|var=="D_notclose"
replace var = "D" if var=="D_close" |var=="D_notclose"
replace var = "oneminusD" if var=="oneminusDn" |var=="oneminusDc"
reshape wide coef ci_* stderr pval* , i( sample) j(var) string

g star  = ""
replace star = "*" if pvalD<0.1
replace star = "**" if pvalD<0.05
replace star = "***" if pvalD<0.01

tostring coefD, generate(te) format( "%9.3fc") force
tostring stderrD, generate(se) format( "%9.3fc") force
g impact = "LATE: " + te + star + " (" + se + ")"
g impact1 = "LATE: " + te + star 
g impact2 = "(" + se + ")"

drop stderr*

foreach v of varlist coefD ci_lowerD ci_upperD {
	replace `v' = `v'+coefoneminusD
}
reshape long coef ci_lower ci_upper count , i( sample impact) j(var) string

replace var = "TCM" if var =="D"
replace var = "CCM" if var =="oneminusD"

replace sample = "1" if sample =="all"
replace sample = "2" if sample =="close"
replace sample = "3" if sample =="not"
destring sample, replace

g sample_1 = sample-.175
g sample_2 = sample+.175


sort   sample     var 

local counter = 2
		foreach sample in all  c n {
			global ${Y}_`sample': di impact[`counter']
			local ++counter
			local ++counter
		}
	
sort sample count var

global title_yearsbyfirst "B. Years of Education by First Presidential"
global title_first_pos_pres "A. First Possible Presidential"

global label_yearsbyfirst "Years of Education"
global label_first_pos_pres "Fraction"

global sc_first_pos_pres "0 .6"
global sc_yearsbyfirst "0 15"

global t_first_pos_pres "(0 (.2) .6)"
global t_yearsbyfirst "(0 (5) 15)"


twoway bar coef sample_1 if var=="CCM", barw(.34) fc("${color_c}%70")  lc("${color_c}") lw(medthick) ///
			|| bar coef sample_2 if var=="TCM", barw(.34) fc("${color_t}%70")  lc("${color_t}") lw(medthick) ///
			|| rcap ci_lower ci_upper sample_1 if var=="CCM",  lc("${color_c}") lw(medium) ///
			|| rcap ci_lower ci_upper sample_2 if var=="TCM",  lc("${color_t}") lw(medium) , ///
			|| scatter coef sample_1 if var=="CCM", ms(i) mlabel(coef) mlabc(black) mlabp(10) mlabf(%9.2f) mlabs(small)  ///		
			|| scatter coef sample_2 if var=="TCM", ms(i) mlabel(coef) mlabc(black) mlabp(10) mlabf(%9.2f) mlabs(small)  ///		
			 ysc(r(${sc_${Y}})) yl${t_${Y}} ysc(extend) xsc(extend) ///
			 ytitle("${lab_${Y}}", size(medium)) ///
			xlabel(1 `" "{bf:All}" "${${Y}_all}"" "' ///
					 2 `"  "{bf:Turn 18 Close to}" "{bf:Presidential Election}" "${${Y}_c}" "' ///
					 3 `"  "{bf:Turn 18 Farther from}" "{bf:Presidential Election}"  "${${Y}_n}" "', labs(medium)) ///
			title("${title_${Y}}", size(medlarge))  ///
			legend(pos(6) row(1) order(1 "Untreated Compliers" 2 "Treated Compliers") size(medium)) ///
			name(close${Y}, replace)
			
	restore
}
	grc1leg2  closefirst_pos_pres closeyearsbyfirst, col(1) xsize(8.5) ysize(11)
	graph export f_close.pdf, replace
	
		grc1leg2 closefirst_pos_pres closeyearsbyfirst, col(2) xsize(11) ysize(5.5)
	graph export f_close_horiz.pdf, replace
	
}
if $tn_voter_detailed == 1 {
*predict instate college using BPS

estimates clear
use  "$data\descriptivesfile_bps9th.dta", clear
keep if atleast18==1
label var baselinefemale "Female"
label var baselineasian "Asian"
label var baselineblack "Black"
label var baselinehisp "Latinx"
label var baselineotherrace "Other race" 
label var baselinewhite "White"
label var baselinesped "Special education"
label var baselinelep "English learner"
label var	baselinefrpl  "Subsidized lunch"
label var   baseline_e "Baseline MCAS ELA"
label var baseline_m "Baseline MCAS Math"
label var   twoyearsout_e "MCAS ELA"
label var twoyearsout_m "MCAS Math"
label var att_any_byY2fall  "Enroll in any college"
label var att_4yr_byY2fall  "Enroll in 4-year college"
label var att_2yr_byY2fall  "Enroll in 2-year college"
label var ever_voted  "Ever voted in MA"
label var first_pos_pres "Voted in first possible presidential"
label var ever_pres  "Ever voted presidential"

drop if charter9==1|charter10==1|charter11==1|charter12==1


*make sure 8th grade is used as baseline
*predict in-state college going
 reghdfe att_MA_byY2 baselinefemale baselineasian baselineblack baselinehisp baselineotherrace baselinesped baselinelep ///
		baselinefrpl c.baseline_m##c.baseline_m##c.baseline_m ///
		if ( baselinemasscode~=.&hasbaselinedemos==1& inbostonbaseline==1 & proj_year>=2006&proj_year12<=2017&atleast18==1) ///
		, absorb(year9 baselineyob)
estimates store predict_col
		
predict col_xb, xb

hist col_xb, by(att_MA_byY2)
bys att_MA_byY2: su col_xb


*predict voting including college status
 reghdfe ever_registered baselinefemale baselineasian baselineblack baselinehisp baselineotherrace baselinesped baselinelep ///
		baselinefrpl c.baseline_m##c.baseline_m##c.baseline_m ///
		att_4yr_byY2fall##att_MA_byY2  att_2yr_byY2fall##att_MA_byY2 ///
		if ( baselinemasscode~=.&hasbaselinedemos==1& inbostonbaseline==1 & proj_year>=2006&proj_year12<=2017&atleast18==1) ///
		, absorb(year9 baselineyob)
estimates store predict_er

 reghdfe share_pres baselinefemale baselineasian baselineblack baselinehisp baselineotherrace baselinesped baselinelep ///
		baselinefrpl c.baseline_m##c.baseline_m##c.baseline_m ///
		att_4yr_byY2fall##att_MA_byY2  att_2yr_byY2fall##att_MA_byY2 ///
		if ( baselinemasscode~=.&hasbaselinedemos==1& inbostonbaseline==1 & proj_year>=2006&proj_year12<=2017&atleast18==1) ///
		, absorb(year9 baselineyob)
estimates store predict_ev

 reghdfe first_pos_pres baselinefemale baselineasian baselineblack baselinehisp baselineotherrace baselinesped baselinelep ///
		baselinefrpl c.baseline_m##c.baseline_m##c.baseline_m ///
		att_4yr_byY2fall##att_MA_byY2  att_2yr_byY2fall##att_MA_byY2 ///
		if ( baselinemasscode~=.&hasbaselinedemos==1& inbostonbaseline==1 & proj_year>=2006&proj_year12<=2017&atleast18==1) ///
		, absorb(year9 baselineyob)
estimates store predict_fpp

voteruse
estimates restore predict_col
predict predictedcol_MA, xb
hist predictedcol_MA, by(att_MA_byY2)
bys att_MA_byY2: su predictedcol_MA


foreach v in er ev fpp{
estimates restore predict_`v'
predict predicted_`v', xb

}

*generate versions of the outcome variables for each of the groups I will tests
ren ever_registered er 
ren share_pres ev 
ren first_pos_pres fpp


g all = 1
foreach v of varlist er ev fpp {
   foreach g in all {
	g `v'_inMA12_`g' = .
	replace  `v'_inMA12_`g' = `v' if boston12!=.&`g'==1
	g `v'_notinMA12_`g' = .
	replace `v'_notinMA12_`g' =`v' if boston12==.&`g'==1
	g `v'_pHI_`g'= .
	replace  `v'_pHI_`g' =`v' if predictedcol_MA!=.&predictedcol_MA>=0.5 &`g'==1
	g `v'_pLO_`g' = .
	replace  `v'_pLO_`g' = `v' if predictedcol_MA!=.&predictedcol_MA<0.5 &`g'==1
	g `v'_inMAc_`g' = .
	replace  `v'_inMAc_`g' = `v' if att_out_byY2!=1 &`g'==1
	g `v'_notMAc_`g' = .
	replace  `v'_notMAc_`g' = `v' if att_out_byY2==1 &`g'==1
	g `v'_both_`g' = .
	replace  `v'_both_`g' = `v' if att_out_byY2!=1&boston12!=. &`g'==1
	g `v'_notboth_`g' = .
	replace  `v'_notboth_`g' = `v' if att_out_byY2==1|boston12==.&`g'==1
}
}

estimates clear
foreach y of varlist er_*   ev_*  fpp_*   {
global Y `y'
	voterreg2 
}

	file open  t	using tn_voter_detailed.tex, replace write
	file write t	"\begin{sidewaystable}[htbp!] \centering" _n "\def\sym#1{\ifmmode^{#1}\else\(^{#1}\)\fi}" _n ///
					"\caption{The Impact of Charter School Attendance on Voting, Sample Restrictions }" _n "\label{tn_voter_detailed}""\small" _n ///
					"\begin{tabular*}{1\textwidth}{@{\extracolsep{\fill}}l*{6}{c}}" _n "\midrule" _n ///
					"&\multicolumn{3}{c}{Expected to Vote in MA}&\multicolumn{3}{c}{ Not Expected to Vote in MA} \\" _n ///
						"\cline{2-4} \cline{5-7} \\" _n  ///
					"&Ever&Share   &Voted in First&Ever&Share    &Voted in First \\" _n ///
					"&Registered&  Presidential&Possible Presidential &Registered& Presidential & Possible Presidential\\" _n ///
					"&(1)&(2)&(3)&(4)&(5)&(6)\\" _n ///
					"\midrule"  _n ///
					"(A) 12th grade status  &\multicolumn{3}{c}{ In MA 12th grade}&\multicolumn{3}{c}{ Not in MA 12th grade} \\" _n " \cmidrule{1-1}"  _n  
file close t

	esttab iv_er_inMA12_all  iv_ev_inMA12_all iv_fpp_inMA12_all	iv_er_notinMA12_all  iv_ev_notinMA12_all iv_fpp_notinMA12_all ///
		using tn_voter_detailed.tex, k($D) coef($D "2SLS ") 		s(ccm N, l("\hspace{.25cm} CCM"   "\hspace{.25cm} \textit{N} " ) f(3 %9.0fc) lay( @  @ )) $opts  

file open  t	using tn_voter_detailed.tex, append write	
file write t	" \cmidrule{1-1}" _n "(B) College location  &\multicolumn{3}{c}{  Not out-of-state college}&\multicolumn{3}{c}{Out-of-state college} \\" _n " \cmidrule{1-1}"  _n  
file close t

	esttab iv_er_inMAc_all  iv_ev_inMAc_all iv_fpp_inMAc_all	iv_er_notMAc_all  iv_ev_notMAc_all iv_fpp_notMAc_all ///
		  using tn_voter_detailed.tex, k($D) coef($D "2SLS ") 		s(ccm N, l("\hspace{.25cm} CCM"   "\hspace{.25cm} \textit{N} " ) f(3 %9.0fc) lay( @  @ )) $opts  

file open  t	using tn_voter_detailed.tex, append write	
file write t	" \cmidrule{1-1}" _n "(C) 12th grade and college  &\multicolumn{3}{c}{Not OOS College + MA 12th grade }&\multicolumn{3}{c}{ OOS college or not  MA 12th} \\" _n " \cmidrule{1-1}"  _n  
file close t

	esttab iv_er_both_all  iv_ev_both_all iv_fpp_both_all	iv_er_notboth_all   iv_ev_notboth_all iv_fpp_notboth_all /// 	
		using tn_voter_detailed.tex, k($D) coef($D "2SLS ") 		s(ccm N, l("\hspace{.25cm} CCM"   "\hspace{.25cm} \textit{N} " ) f(3 %9.0fc) lay( @  @ )) $opts  


file open  t	using tn_voter_detailed.tex, append write	
file write t	" \cmidrule{1-1}" _n "(D) Predicted likelihood of MA college &\multicolumn{3}{c}{High predicted MA college  }&\multicolumn{3}{c}{ Low predicted MA college  } \\" _n " \cmidrule{1-1}"  _n  
file close t

	esttab iv_er_pHI_all  iv_ev_pHI_all iv_fpp_pHI_all	iv_er_pLO_all   iv_ev_pLO_all iv_fpp_pLO_all /// 	
		using tn_voter_detailed.tex, k($D) coef($D "2SLS ") 		s(ccm N, l("\hspace{.25cm} CCM"   "\hspace{.25cm} \textit{N} " ) f(3 %9.0fc) lay( @  @ )) $opts  

	file open  t 	using tn_voter_detailed.tex, append write
	file write t 		"\midrule" _n "\end{tabular*}" _n ///
					"\begin{tabular*}{1\textwidth}{p{8.4in}}" _n ///
					"\footnotesize Notes:  " ///
					"This table varies the sample of students in the regressions, all other notes are the same as in Online Appendix Table \ref{tn_voter}. " ///
					"Predicted likelihood of attending an MA college is calculated in the non-charter BPS sample, with predicted values applied to the charter lottery population. " ///
					"$note_stars" ///
					"\end{tabular*}" _n "\end{sidewaystable}" _n 
	file close t
	
	
}
if $tn_voter_imputed == 1 {
*predict voting using college goers in using Charter lottery loser who do not attend charters

estimates clear

*BEGIN with lottery losers
voteruse

keep if initial_offer_s==0&waitlist_offer_s==0& ever_blottocharter==0

*predict voting if attend college in MA
foreach n of numlist 2 4{
 reghdfe ever_registered baselinefemale baselineasian baselineblack baselinehisp baselineotherrace baselinesped baselinelep ///
		baselinefrpl c.baseline_m##c.baseline_m##c.baseline_m ///
		if (att_`n'yr_byY2fall==1&  att_MA_byY2fall==1 & baselinemasscode~=.&hasbaselinedemos==1& inbostonbaseline==1 & proj_year>=2006&proj_year12<=2017&atleast18==1) ///
		, absorb(year9 baselineyob)
estimates store predict_er_MA`n'

 reghdfe share_pres baselinefemale baselineasian baselineblack baselinehisp baselineotherrace baselinesped baselinelep ///
		baselinefrpl c.baseline_m##c.baseline_m##c.baseline_m ///
		if (att_`n'yr_byY2fall==1&  att_MA_byY2fall==1 & baselinemasscode~=.&hasbaselinedemos==1& inbostonbaseline==1 & proj_year>=2006&proj_year12<=2017&atleast18==1) ///
		, absorb(year9 baselineyob)
estimates store predict_ev_MA`n'

 reghdfe first_pos_pres baselinefemale baselineasian baselineblack baselinehisp baselineotherrace baselinesped baselinelep ///
		baselinefrpl c.baseline_m##c.baseline_m##c.baseline_m ///
		if (att_`n'yr_byY2fall==1&  att_MA_byY2fall==1 & baselinemasscode~=.&hasbaselinedemos==1& inbostonbaseline==1 & proj_year>=2006&proj_year12<=2017&atleast18==1) ///
		, absorb(year9 baselineyob)
estimates store predict_fpp_MA`n'
}

*predictions for no college
 reghdfe ever_registered baselinefemale baselineasian baselineblack baselinehisp baselineotherrace baselinesped baselinelep ///
		baselinefrpl c.baseline_m##c.baseline_m##c.baseline_m ///
		if (att_any_byY2fall==0& baselinemasscode~=.&hasbaselinedemos==1& inbostonbaseline==1 & proj_year>=2006&proj_year12<=2017&atleast18==1) ///
		, absorb(year9 baselineyob)
estimates store predict_er_nocol

 reghdfe share_pres baselinefemale baselineasian baselineblack baselinehisp baselineotherrace baselinesped baselinelep ///
		baselinefrpl c.baseline_m##c.baseline_m##c.baseline_m ///
		if (att_any_byY2fall==0 & baselinemasscode~=.&hasbaselinedemos==1& inbostonbaseline==1 & proj_year>=2006&proj_year12<=2017&atleast18==1) ///
		, absorb(year9 baselineyob)
estimates store predict_ev_nocol

 reghdfe first_pos_pres baselinefemale baselineasian baselineblack baselinehisp baselineotherrace baselinesped baselinelep ///
		baselinefrpl c.baseline_m##c.baseline_m##c.baseline_m ///
		if ( att_any_byY2fall==0&baselinemasscode~=.&hasbaselinedemos==1& inbostonbaseline==1 & proj_year>=2006&proj_year12<=2017&atleast18==1) ///
		, absorb(year9 baselineyob)
estimates store predict_fpp_nocol

	
voteruse

ren ever_registered er
ren share_pres ev
ren first_pos_pres fpp

foreach v in er ev fpp{
g `v'_imputeREG=`v'
g `v'_imputeREGn=`v'
g `v'_imputeREG2=.

	foreach n in 2 4{
estimates restore predict_`v'_MA`n'
predict predicted_`v'_MA`n', xb

replace `v'_imputeREG = predicted_`v'_MA`n' if (att_`n'yr_byY2fall==1&  att_out_byY2fall==1) //out-of-state only
replace `v'_imputeREGn = predicted_`v'_MA`n' if (att_`n'yr_byY2fall==1&  att_out_byY2fall==1&college_state!=  9 &college_state!=  9  &college_state!= 23  &college_state!= 33  &college_state!= 36    &college_state!= 36  &college_state!= 50 ) //out-of-state only
replace `v'_imputeREG2 = predicted_`v'_MA`n' if (att_`n'yr_byY2fall==1) //impute for all
}
estimates restore predict_`v'_nocol
predict predicted_`v'_nocol, xb
replace `v'_imputeREG = 0 if  `v'_imputeREG ==.
replace `v'_imputeREG2 =predicted_`v'_nocol if `v'_imputeREG2  ==. //impute for all
*this is wrong replace `v'_imputeREG2 = 0 if  `v'_imputeREG2 ==.

g `v'_impute0 = `v'
replace `v'_impute0=0 if  att_out_byY2fall==1

g `v'_impute1 = `v'
replace `v'_impute1=1 if  att_out_byY2fall==1
}

foreach y of varlist er ev fpp *impute* {
	g `y'_all = `y'
}

foreach y of varlist  ev_all  ev_impute0_* ev_imputeREG_* ev_imputeREGn_* fpp_all  fpp_impute0_* fpp_imputeREG_* fpp_imputeREGn_*  {
	global Y `y'
	voterreg2 
}

count 
local n = string( r(N), "%9.0fc")

count if baselinefemale==1
local ng = string( r(N), "%9.0fc")

count if baselinefemale==0 
local nb = string( r(N), "%9.0fc")


	file open  t	using tn_voter_imputed.tex, replace write
	file write t	"\begin{table}[htbp!] \centering" _n "\def\sym#1{\ifmmode^{#1}\else\(^{#1}\)\fi}" _n ///
					"\caption{The Impact of Charter School Attendance on Voting, with Imputations for Out-of-State College Attendees }" _n "\label{tn_voter_imputed} \small" _n ///
					"\begin{tabular*}{1\textwidth}{@{\extracolsep{\fill}}l*{2}{c}}" _n "\midrule" _n ///
					"&Share Presidential&First Presidential\\" _n ///
					"&(1)&(2)\\" _n ///
					"\midrule"  _n	///
					"(A) Main specification, missing voting = 0 \\" _n "\midrule" _n  
file close t

	esttab iv_ev_all  iv_fpp_all ///
		using tn_voter_imputed.tex, k($D) coef($D "2SLS ") 		s(ccm , l( "\hspace{.25cm} CCM"    "" ) f(3 ) lay( @   `""' )) $opts  

file open  t	using tn_voter_imputed.tex, append write	
file write t	" \cmidrule{1-1}" _n "(B) Out-of-state college attendees imputed with 0  \\" _n "\cmidrule{1-1}" _n  
file close t

	esttab iv_ev_impute0_all  iv_fpp_impute0_all ///
		  using tn_voter_imputed.tex, k($D) coef($D "2SLS ") 	s(ccm , l( "\hspace{.25cm} CCM"    "" ) f(3 ) lay( @   `""' )) $opts  

file open  t	using tn_voter_imputed.tex, append write	
file write t	" \cmidrule{1-1}" _n "(C) Out-of-state college attendees imputed with predicted  \\" _n "\cmidrule{1-1}" _n  
file close t

	esttab iv_ev_imputeREG_all  iv_fpp_imputeREG_all  ///
		using tn_voter_imputed.tex, k($D) coef($D "2SLS ") 		s(ccm , l( "\hspace{.25cm} CCM"    "" ) f(3 ) lay( @   `""' )) $opts  


file open  t	using tn_voter_imputed.tex, append write	
file write t	" \cmidrule{1-1}" _n "(D) Out-of-nearby-states college attendees imputed with predicted  \\" _n "\cmidrule{1-1}" _n  

file close t

	esttab iv_ev_imputeREGn_all iv_fpp_imputeREGn_all  ///
		using tn_voter_imputed.tex, k($D) coef($D "2SLS ") 		s(ccm , l( "\hspace{.25cm} CCM"    "" ) f(3 ) lay( @   `""' )) $opts  
		
file open  t	using tn_voter_imputed.tex, append write	
	file write t 		"\midrule" _n "\end{tabular*}" _n ///
					"\begin{tabular*}{1\textwidth}{p{6.3in}}" _n ///
					"\footnotesize Notes:  " ///
					"This table varies shows various imputations for out-of-state college attendees. In the main specification, individuals missing voting information are assumed to be non-registrants or non-voters. In the imputed specifications, out-of-state college attendees have various values imputed for their registration and voting statuses, as indicated in the headers. Predicted status is based on the regression adjusted registration/voting rates of Boston charter lottery applicant college attendees, who did not receive an offer and did not attend a charter school, separately for 2- and 4-year institutions. All other notes and sample sizes are the same as in Online Appendix Table \ref{tn_voter}. \textit{N} = `n'.  " ///
					"$note_stars" ///
					"\end{tabular*}" _n "\end{table}" _n 
	file close t
	
}
if $tn_community==1{
estimates clear

global setup_community		1
global analysis_community 	1

if $setup_community == 1{
	
use  "$data\descriptivesfile_ma9th.dta", clear
keep sasid masscode12 year12 baselinefemale ID_FSC_firstinst
drop if ID_FSC_firstinst==""
drop if masscode12==.
collapse (count) sasid, by(masscode12 year12 baselinefemale ID_FSC_firstinst)
ren sasid count

save collegecountssolo.dta, replace

 

use  "$data\descriptivesfile_ma9th.dta", clear
keep if atleast18==1

label var ever_voted  "Ever voted in MA"
label var first_pos_pres "Voted in first possible presidential"

drop if charter9==1|charter10==1|charter11==1|charter12==1


ren ever_registered er
ren ever_pres ev
ren first_pos_pres fpp

replace opeid=99999999 if opeid==. & boston9==1


keep if opeid!=. 


ren er col_er
ren ev col_ev
ren fpp col_fpp

preserve
*individual level
collapse (mean) col_* (count) count = sasid , by(opeid institution_name)

keep if count>=25

save college_votes_ma.dta, replace

restore

*sector level for those with too small a sample sizes
*modify with barrons later
collapse (mean) col_* (count) count = sasid , by(college_MA college_public college_private college_4yr college_2yr    )

ren col_* imputed_col_*

drop if count<25
drop count
save college_type_votes_ma.dta, replace


*back to main data

voteruse
merge m:1 masscode12 year12 baselinefemale ID_FSC_firstinst  using collegecountssolo.dta, keep(1 3)

g solo = count==1

ren ever_registered er
ren ever_pres ev
ren first_pos_pres fpp

replace opeid=99999999 if opeid==. 


foreach v of varlist college_MA college_any college_public college_private college_4yr college_2yr{
	replace `v' = 0 if `v' ==.
}

merge m:1 opeid institution_name using college_votes_ma.dta  ,  keep(1 3) nogen


merge m:1 college_MA college_public college_private college_4yr college_2yr  using college_type_votes_ma.dta,  keep(1 3) nogen


foreach v in er ev  fpp{
    replace col_`v' = imputed_col_`v' if col_`v'==. &opeid!=99999999
 }
 

 *Dave Leip Data
 merge 1:1 sasid using "$data\dave_leip.dta", nogen keep(1 3)
 
 save  "$data\baseanalysisfile_voter_lotto_community.dta", replace

}
if $analysis_community == 1{
	
	 use  "$data\baseanalysisfile_voter_lotto_community.dta", clear
	 
	 estimates clear

ren att_4yr_byY2fall college
ren att_4yr_byY3fall persistence
ren att_any_byY2fall coll_any

ren k_mean colqual //don't seperate by gender


foreach y of varlist col_er col_ev col_fpp reg_total_county turnout_reg_county  colqual   persistence  solo  {

global Y `y'
	voterreg2 
	
}


	file open  t	using tn_community.tex, replace write
	file write t	"\begin{sidewaystable}[htbp!] \centering" _n "\def\sym#1{\ifmmode^{#1}\else\(^{#1}\)\fi}" _n ///
					"\caption{The Impact of Charter School Attendance on College-Community Civic Participation and Other College Outcomes}" _n "\small \label{tn_community}" _n ///
					"\begin{tabular*}{1\textwidth}{@{\extracolsep{\fill}}l*{8}{c}}" _n "\midrule" _n ///
				"&\multicolumn{5}{c}{College-Community Civic Participation}&\multicolumn{3}{c}{Other College Outcomes} \\" _n ///
							"\cline{2-6} \cline{7-9}  \\" _n ///
			"&College&College   &College First&County &County&&&Solo\\" _n ///
					"&Registration&Ever Voting   & Presidential&Registration&Turnout&College&College	&  College\\" _n ///
					"&Rate&Rate &  Rate& Rate&Rate&Quality&Persistence&Attendee\\\" _n ///
					"&(1)&(2)&(3)&(4)&(5)&(6)&(7)&(8)\\" _n ///
					"\midrule"  _n	
file close t

	esttab iv_* using tn_community.tex, k($D) coef($D "2SLS ") 		s(ccm N, l( "\hspace{.25cm} CCM" ""  " \hspace{.25cm} \textit{N} " ) f(3 %9.0fc) lay(@   `""'  @)) $opts  

file open  t	using tn_community.tex, append write	
	file write t 			"\midrule" _n "\end{tabular*}" _n ///
					"\begin{tabular*}{1\textwidth}{p{8.4in}}" _n ///
					"\footnotesize Notes:  " ///
					"The outcomes here substitute college or community registration/voting rates for individual voter behavior, with voting rates based on the voting patterns of non-charter Massachusetts students or county level measures (based on college location). 		" /// 	
			"College quality is the estimated 2014 earnings of college attendees from the 1980-1982 birth cohorts from Chetty, et al. (2017).  " ///
			"Solo college attendee means that the student is the only person from their gender and high school attending their college. " ///
"All other notes are the same as in Online Appendix Table \ref{tn_voter} and \ref{attainment}. " ///
					"\end{tabular*}" _n "\end{sidewaystable}" _n 
	file close t
		
}

}
if $fn_mission == 1{

estimates clear
clear
g save = 1
save civic_first_pos_pres, replace
save civic_share_pres, replace

	
foreach v in first_pos_pres	share_pres {
	
voteruse
		
	*civic and noncivic lottery code up done in voter setup file 
	g oneminusDc = 1-D_civic
	g oneminusDn = 1-D_notcivic
	global Y `v'
global lab_${Y} : variable label ${Y}
qui g ${Y}c_Y0=${Y}*oneminusDc
qui g ${Y}n_Y0=${Y}*oneminusDn

 eststo iv_${Y}: ivreg2 ${Y} (D_civic D_notcivic = ///
				initial_offer_civic waitlist_offer_civic initial_offer_notcivic waitlist_offer_notcivic) ///
				$covariates $risksets  if  voter_sample==1 ///
		, partial($covariates  $risksets ) robust 

test D_civic = D_notcivic
local p = r(p)	
			qui estadd scalar p=`p'
	global p_${Y} = string(r(p),  "%9.3f")
	di in yellow "p-value for ${Y}: ${p_${Y}}"
preserve
	qui regsave using civic_`v', ci pval  addlabel(outcome, `y', pvalcn,  ${p_${Y}})  append
restore			
 qui  ivreg2 ${Y}c_Y0 (oneminusDc oneminusDn =  ///
		initial_offer_civic waitlist_offer_civic initial_offer_notcivic waitlist_offer_notcivic) ///
		$covariates  $risksets if  voter_sample==1 ///
		, partial($covariates  $risksets ) robust 	
preserve
	qui regsave using civic_`v', ci pval addlabel(outcome, `y', pvalcn,  ${p_${Y}})  append
restore				
  qui ivreg2 ${Y}n_Y0 (oneminusDc oneminusDn =  ///
		initial_offer_civic waitlist_offer_civic initial_offer_notcivic waitlist_offer_notcivic) ///
		$covariates  $risksets  if  voter_sample==1 ///
		, partial($covariates  $risksets ) robust 
preserve
	qui regsave using civic_`v', ci pval addlabel(outcome, `y', pvalcn,  ${p_${Y}})  append
restore				
}
foreach v in first_pos_pres	share_pres {
global Y `v'
use main.dta, clear
keep if sample == "all" & (outcome=="`v'")
append using civic_`v'.dta
drop outcome  N  r2
drop if coef<= 0 //these are the extra CCMs from the two endog model 
replace sample = "civic" if var == "oneminusDc"|var=="D_civic"
replace sample = "not" if var == "oneminusDn"|var=="D_notcivic"
replace var = "D" if var=="D_civic" |var=="D_notcivic"
replace var = "oneminusD" if var=="oneminusDn" |var=="oneminusDc"
reshape wide coef ci_* stderr pval* , i( sample) j(var) string

g star  = ""
replace star = "*" if pvalD<0.1
replace star = "**" if pvalD<0.05
replace star = "***" if pvalD<0.01

tostring coefD, generate(te) format( "%9.3fc") force
tostring stderrD, generate(se) format( "%9.3fc") force
g impact = "LATE: " + te + star + " (" + se + ")"
g impact1 = "LATE: " + te + star 
g impact2 = "(" + se + ")"

drop stderr*

foreach v of varlist coefD ci_lowerD ci_upperD {
	replace `v' = `v'+coefoneminusD
}
reshape long coef ci_lower ci_upper count , i( sample impact) j(var) string

replace var = "TCM" if var =="D"
replace var = "CCM" if var =="oneminusD"

replace sample = "1" if sample =="all"
replace sample = "2" if sample =="civic"
replace sample = "3" if sample =="not"
destring sample, replace

g sample_1 = sample-.175
g sample_2 = sample+.175


sort   sample     var 

local counter = 2
		foreach sample in all  c n {
			global ${Y}_`sample': di impact[`counter']
			local ++counter
			local ++counter
		}
	
sort sample count var

global title_share_pres "A. Share Presidential"
global title_first_pos_pres "B. First Possible Presidential"


twoway bar coef sample_1 if var=="CCM", barw(.34) fc("${color_c}%70")  lc("${color_c}") lw(medthick) ///
			|| bar coef sample_2 if var=="TCM", barw(.34) fc("${color_t}%70")  lc("${color_t}") lw(medthick) ///
			|| rcap ci_lower ci_upper sample_1 if var=="CCM",  lc("${color_c}") lw(medium) ///
			|| rcap ci_lower ci_upper sample_2 if var=="TCM",  lc("${color_t}") lw(medium) , ///
			|| scatter coef sample_1 if var=="CCM", ms(i) mlabel(coef) mlabc(black) mlabp(10) mlabf(%9.2f) mlabs(small)  ///		
			|| scatter coef sample_2 if var=="TCM", ms(i) mlabel(coef) mlabc(black) mlabp(10) mlabf(%9.2f) mlabs(small)  ///		
			yscale(r(0 .63)) ysc(extend) xsc(extend) ///
			yl(0(.2).6, labs(medsmall)) ytitle("Fraction", size(medium)) ///
			xlabel(1 `" "{bf:All}" "${${Y}_all}"" "' ///
					 2 `"  "{bf:Civics-Oriented}" "{bf:Mission Statements}" "${${Y}_c}" "' ///
					 3 `"  "{bf:Non-Civics-Oriented}" "{bf:Mission Statements}"  "${${Y}_n}" "', labs(medium)) ///
			title("${title_${Y}}", size(medlarge))  ///
			legend(pos(6) row(1) order(1 "Untreated Compliers" 2 "Treated Compliers") size(medium)) ///
			name(civics${Y}, replace)
			

	
}
	grc1leg2 civicsshare_pres civicsfirst_pos_pres, col(1) xsize(8.5) ysize(11)
	graph export f_civic.pdf, replace
	
		grc1leg2 civicsshare_pres civicsfirst_pos_pres, col(2) xsize(11) ysize(5.5)
	graph export f_civic_horiz.pdf, replace
}	
if $tn_mission == 1{
	voteruse
		
	*civic and noncivic lottery code up done in voter setup file 
	
	g oneminusDc = 1-D_civic
	g oneminusDn = 1-D_notcivic
	
	
foreach v of varlist $shortvote took_ushistgov above_s3_ushistgov {
	global Y `v'
global lab_${Y} : variable label ${Y}
qui g ${Y}c_Y0=${Y}*oneminusDc
qui g ${Y}n_Y0=${Y}*oneminusDn

 qui  ivreg2 ${Y}c_Y0 (oneminusDc oneminusDn =  ///
		initial_offer_civic waitlist_offer_civic initial_offer_notcivic waitlist_offer_notcivic) ///
		$covariates  $risksets if  voter_sample==1 ///
		, partial($covariates  $risksets ) robust 
			local ccm_c = _b[oneminusDc]
			
  qui ivreg2 ${Y}n_Y0 (oneminusDc oneminusDn =  ///
		initial_offer_civic waitlist_offer_civic initial_offer_notcivic waitlist_offer_notcivic) ///
		$covariates $risksets  if  voter_sample==1 ///
		, partial($covariates  $risksets ) robust 
			local ccm_n = _b[oneminusDn]
		
 eststo iv_${Y}: ivreg2 ${Y} (D_civic D_notcivic = ///
				initial_offer_civic waitlist_offer_civic initial_offer_notcivic waitlist_offer_notcivic) ///
				$covariates  $risksets  if  voter_sample==1 ///
		, partial($covariates  $risksets ) robust 
		qui estadd scalar ccm_c=`ccm_c'
			qui estadd scalar ccm_n=`ccm_n'
	
	global n_${Y}= string(e(N), "%9.0fc")
	
test D_civic = D_notcivic
local p = r(p)	
			qui estadd scalar p=`p'
		
			}
			

	
	file open  t	using tn_mission_reg.tex, replace write
	file write t	"\begin{table}[htbp!] \centering" _n "\def\sym#1{\ifmmode^{#1}\else\(^{#1}\)\fi}" _n ///
					"\caption{The Impact of Charter School Attendance on Voting, by Civics-Oriented Charter School Mission Statements }" _n "\small \label{tn_mission_reg}" _n ///
					"\begin{tabular*}{1\textwidth}{@{\extracolsep{\fill}}l*{5}{c}}" _n "\midrule" _n ///
					"&Ever&Share &Voted in First &Took AP&Score 3+ AP\\" _n ///
					"&Registered& Presidential & Possible Presidential&US Hist or Gov&US Hist or Gov\\" _n ///
					"&(1)&(2)&(3)\\" _n ///
					"\midrule"  _n	
file close t

	esttab iv_ever_registered iv_share_pres iv_first_pos_pres iv_took_ushistgov iv_above_s3_ushistgov	using tn_mission_reg.tex, k(D_civic ) coef(D_civic  "Mission Statement with Civics") 		s(ccm_c  , l( "\hspace{.25cm} CCM"  ) f(3  ) lay( @  `""'  )) $opts  
	esttab iv_ever_registered iv_share_pres iv_first_pos_pres iv_took_ushistgov iv_above_s3_ushistgov	using tn_mission_reg.tex, k(D_notcivic ) coef(D_notcivic  "Mission Statement without Civics") 		s(ccm_n     N p , l( "\hspace{.25cm} CCM"   "" "\hspace{.25cm} \textit{N} " "" "\textit{p}-value") f(3 %9.0fc 3  ) lay( @  `""' @ `""' @  )) $opts  
		
file open  t	using tn_mission_reg.tex, append write	
	file write t 		"\midrule" _n "\end{tabular*}" _n ///
					"\begin{tabular*}{1\textwidth}{p{6.3in}}" _n ///
					"\footnotesize Notes: This table shows a modified version of the main specification, in which the endogenous variable and offer variables are accounted for separately for charter schools with mission statements with civics orientations and for those without.  " ///
					" All other notes are the same as in Online Appendix Tables \ref{tn_academic} and \ref{tn_voter}. See Online Appendix Table \ref{tn_mission_statement} for details on categorization of mission statements. " ///
					"The \textit{p}-value from a test of equality of the civics-oriented and non-civics-oriented coefficients is listed in the final row of the table. $note_stars" ///
					"\end{tabular*}" _n "\end{table}" _n 
	file close t
	
*Note -- table describing mission statements is in Overleaf

	
}
if $tn_voter_sub == 1{
	//subgroups
voteruse
estimates clear
 
 g all = 1
 
 //in sample median
bys baselinegrade baselineyear: egen median = median(baseline_m) //do based on math since greater years of coverage
 g above_baseline = baseline_m>=median & baseline_m!=.
 g below_baseline = above_baseline==0  //includes missings
 
 g notspecial = baselinesped==0&baselinelep==0& baselinesped!=.
 
 g notlunch = baselinefrpl==0 &baselinefrpl!=.
  
 g nonblackorhisp =( baselinewhite ==1|baselineasian==1| baselineotherrace )&baselineblack!=.
 d
 foreach group in above_baseline below_baseline baselinesped baselinelep notspecial baselinefrpl notlunch   ///
	baselineblack baselinehisp baselinewhite baselineasian baselineotherrace  nonblackorhisp {
g reg_`group'= ever_registered if `group'==1
g vote_`group'= share_pres if `group'==1
g fpp_`group'= first_pos_pres if `group'==1
   global Y reg_`group'
	voterreg2 
	
  global Y vote_`group'
	voterreg2 
	
 global Y fpp_`group'
	voterreg2 
	}


file open  t	using tn_voter_sub.tex, replace write
	file write t	"\begin{sidewaystable}[htbp!] \centering" _n "\def\sym#1{\ifmmode^{#1}\else\(^{#1}\)\fi}" _n ///
					"\caption{The Impact of Charter School Attendance on Voting, by Subgroups }" _n " \small \label{tn_voter_sub}" _n ///
					"\begin{tabular*}{1\textwidth}{@{\extracolsep{\fill}}l*{10}{c}}" _n "\midrule" _n ///
					"&		&		&  &					&Not &Free/&Not && &White, \\" _n ///
					"&High		&Low		&Special  &English& Special&Reduced& F/R && &Asian, and \\" _n ///
					"&Scorers	&Scorers	& Education&Learner&Needs &Lunch&Lunch&Black&Latinx & Other Race \\" _n ///
					"&(1)&(2)&(3)&(4)&(5)&(6)&(7)&(8)&(9)&(10)\\" _n ///
					"\midrule"  _n 
file close t

	esttab   iv_reg_above_baseline  iv_reg_below_baseline iv_reg_baselinesped iv_reg_baselinelep iv_reg_notspecial iv_reg_baselinefrpl iv_reg_notlunch iv_reg_baselineblack iv_reg_baselinehisp iv_reg_nonblackorhisp	///
		using tn_voter_sub.tex, k($D) coef($D "Ever Registered (2SLS)") 		s(ccm , l( "\hspace{.25cm} CCM"  ""  ) f(3 ) lay( @ `""'  )) $opts  
	esttab   iv_vote_above_baseline  iv_vote_below_baseline iv_vote_baselinesped iv_vote_baselinelep iv_vote_notspecial iv_vote_baselinefrpl iv_vote_notlunch	iv_vote_baselineblack iv_vote_baselinehisp iv_vote_nonblackorhisp ///
		 	using tn_voter_sub.tex, k($D) coef($D "Share Presidential (2SLS)") 		s(ccm , l( "\hspace{.25cm} CCM"  ""  ) f(3 ) lay( @ `""'  )) $opts  
	esttab   iv_fpp_above_baseline  iv_fpp_below_baseline iv_fpp_baselinesped iv_fpp_baselinelep iv_fpp_notspecial iv_fpp_baselinefrpl iv_fpp_notlunch  iv_fpp_baselineblack iv_fpp_baselinehisp iv_fpp_nonblackorhisp	///
			using tn_voter_sub.tex, k($D) coef($D "First Pos. Pres.(2SLS) ") s(ccm N, l( "\hspace{.25cm} CCM"  "" "\hspace{.25cm} \textit{N} " ) f(3 %9.0fc) lay( @ `""' @ )) $opts  
	
	file open  t 	using tn_voter_sub.tex, append write
	file write t 	"\midrule" _n "\end{tabular*}" _n ///
					"\begin{tabular*}{1\textwidth}{p{8.4in}}" _n ///
					"\footnotesize Notes:  This table shows 2SLS estimates for subgroups of students from regressions limited to the sample listed in the header. Students categorized as ``not special needs'' are neither special education nor English learner students.  White, Asian, and other race students are combined into a single category due to small sample sizes in these groups. " ///
					"All other notes are the same as in Online Appendix Table \ref{tn_voter}. " ///
					"$note_stars" ///
					"\end{tabular*}" _n "\end{sidewaystable}" _n 
	file close t
	

	
	
}
if $fn_voter_sub == 1{
	//subgroups
	estimates clear
clear
g save = 1
save sub_first_pos_pres, replace
save sub_share_pres, replace

foreach v in first_pos_pres share_pres{
voteruse
 
 g all = 1
 //in sample median
bys baselinegrade baselineyear: egen median = median(baseline_m) //do based on math since greater years of coverage
 g above_baseline = baseline_m>=median & baseline_m!=.
 g below_baseline = above_baseline==0  //includes missings
 
 g notspecial = baselinesped==0&baselinelep==0& baselinesped!=.
 
 g notlunch = baselinefrpl==0 &baselinefrpl!=.
  
 g nonblackorhisp =( baselinewhite ==1|baselineasian==1| baselineotherrace )&baselineblack!=.
 
 g boy = baselinefemale==0
 g girl = baselinefemale==1
 
 foreach group in all boy girl below_baseline above_baseline  baselinesped baselinelep notspecial baselinefrpl notlunch   ///
	baselineblack baselinehisp   nonblackorhisp {

g fpp_`group'= `v' if `group'==1
	
 global Y fpp_`group'
endog

qui eststo iv_${Y}: ivreg2 ${Y} (D = $Z1 $Z2) $covariates $risksets if  voter_sample==1 , partial($covariates  $risksets) robust
preserve
	qui regsave using sub_`v', ci pval addlabel(group, `group')  append
restore	
	}
}

foreach v in first_pos_pres share_pres{

use "$output/sub_`v'.dta", clear
drop save r2  var

g star  = ""
replace star = "*" if pval<0.1
replace star = "**" if pval<0.05
replace star = "***" if pval<0.01

tostring coef, generate(te) format( "%9.3fc") force
tostring stderr, generate(se) format( "%9.3fc") force
g impact1 =  te + star 
g impact2 = "(" + se + ")"

g count =( _N-_n )+1
sort count

g sample = 0
replace sample = 14 if group =="all"
replace sample = 13.1 if group =="girl"
replace sample = 12.5 if group =="boy"
replace sample = 11.6 if group =="above_baseline"
replace sample = 11 if group =="below_baseline"
replace sample = 10.1 if group =="baselinefrpl"
replace sample = 9.5 if group =="notlunch"
replace sample = 8.6 if group =="baselinesped"
replace sample = 8 if group =="baselinelep"
replace sample = 7.4 if group =="notspecial"
replace sample = 6.5 if group =="baselineblack"
replace sample = 5.9 if group =="baselinehisp"
replace sample = 5.3 if group =="nonblackorhisp"

g color = 1 if group =="all" | group =="girl" | group=="above_baseline" | group=="baselinefrpl" |group=="baselinesped" | group =="baselineblack"
replace  color = 2 if  group =="boy" | group=="below_baseline" | group=="notlunch" |group=="baselinelep" | group =="baselinehisp"
replace  color = 3 if  group=="notspecial" | group =="nonblackorhisp"

global title_share_pres "A. Share Presidential"
global title_first_pos_pres "B. First Possible Presidential"

global xline_share_pres 0.051
global xline_first_pos_pres 0.059


twoway scatter   sample  coef if color==1 , mc("${color_1}") m(O) ///
	|| rcap     ci_lower ci_upper sample if color==1, lc("${color_1}") horizontal ///
	|| scatter   sample  coef if color==2 , mc("${color_2}") m(S) ///
	|| rcap     ci_lower ci_upper sample if color==2, lc("${color_2}") horizontal ///
	|| scatter   sample  coef if color==3 , mc("${color_3}") m(T) ///
	|| rcap     ci_lower ci_upper sample if color==3, lc("${color_3}") horizontal ///
	|| scatter sample coef , ms(i) mlabel(impact1) mlabc(black) mlabp(6)  mlabf(%9.2f) mlabs(vsmall)  ///		
	legend(off) xline(0, lc(gray) lp(shortdash_dot)) xlab(-.1(.1).3, labs(medium)) xlab(${xline_`v'} "All", add labs(small)) ///
	xline(${xline_`v'} , lc("${color_1}")) ///
	title(${title_`v'}) ///
	xtitle(LATE (Percentage Points), size(medium)) ytitle("") ysc(r(5 14)) ysc(extend) xsc(extend) ///
	ylabel(14 `" "All" ""' 13.1 `" "Girls" ""' 12.5 `" "Boys" ""' ///
	 11.6 `" "Higher Scoring" ""' 11 `" "Lower Scoring" ""' ///
		10.1 `" "Subsidized Lunch" ""' 9.5 `" "Not Subsidized Lunch" ""' ///
		8.6 `" "Special Education" ""' 8 `" "English Learners" ""' ///
		7.4 `" "Not Special Needs" ""' 6.5 `" "Black" ""' ///
		5.96 `" "Hispanic" ""' 	5.3 `" "Not Black or Hispanic" ""' , labs(medsmall)) xsize(7) ysize(4) name(sub_`v', replace)
}

	graph combine sub_share_pres sub_first_pos_pres, col(1) xsize(8.5) ysize(11)
	graph export f_sub.pdf, replace
	
		graph combine sub_share_pres sub_first_pos_pres, col(2) xsize(11) ysize(5.5)
	graph export f_subc_horiz.pdf, replace

}	
if $f_cog_noncog==1{
	
use  "$data\descriptivesfile_bps9th.dta", clear
*From Jackson (2018): the log of the number of absences in ninth grade (plus 1), whether the student was suspended during ninth grade, the GPA (based on all ninth-grade courses), and whether the student enrolled in tenth grade on time. These behaviors are strongly associated with well-known psychometric measures of noncognitive skills including the "big five" and grit.9 Informed by Heckman et al. (2006), I use a principal component model to create a single index of these behaviors. This index is a weighted average of the non–test score outcomes and is standardized to be mean zero and unit variance. I refer to this index as the behavior index.10

*Out of sample PCA

keep if atleast18==1&baselinefemale!=.	
g susp9 = day_suspension9>0&bps9==1
pca attend9 ontime10 susp9
estimates store noncog
/*
    --------------------------------------------
        Variable |    Comp1     Comp2     Comp3 
    -------------+------------------------------
         attend9 |   0.6815    0.2027   -0.7032 
        ontime10 |   0.6873    0.1527    0.7101 
           susp9 |  -0.2513    0.9673    0.0353 
    --------------------------------------------
*/
  
pca twoyearsout_m twoyearsout_e
estimates store cog

pca share_pres first_pos_pres
estimates store vote

clear
g save = 1
save sub_vote, replace
save sub_noncog, replace
save sub_cog, replace
save sub_attend, replace
save sub_plans_4yr, replace

voteruse

*extra sims
merge 1:1 sasid using "$data_clean/extra_sims.dta", nogen keep(1 3)
label var plans_4yr "Aspirations"

g susp9 = day_suspension9>0&present9!=.

foreach g in noncog cog vote{
	estimates restore `g'
	predict `g', score
}
 
*groups
 g all = 1
bys baselinegrade baselineyear: egen median = median(baseline_m) //do based on math since greater years of coverage
 g above_baseline = baseline_m>=median & baseline_m!=.
 g below_baseline = above_baseline==0  //includes missings
 g notspecial = baselinesped==0&baselinelep==0& baselinesped!=.
 g notlunch = baselinefrpl==0 &baselinefrpl!=.
 g nonblackorhisp =( baselinewhite ==1|baselineasian==1| baselineotherrace )&baselineblack!=.
 g boy = baselinefemale==0
 g girl = baselinefemale==1
 
 
 label var all "All"
 label var girl "Girls"
 label var boy "Boys"
 label var below_baseline "Lower Scoring"
  label var above_baseline "Higher Scoring"
  label var baselinesped "Special Ed"
  label var baselinelep "EL"
  label var notspecial "Not Special Needs" 
  label var baselinefrpl "Higher Poverty"
  label var notlunch "Lower Poverty"
  label var baselineblack "Black"
  label var baselinehisp "Hispanic"
  label var nonblackorhisp  "Not Black/Hispanic"
  
  egen attend=std(attend9)

foreach v in vote noncog cog attend plans_4yr {

cap drop fpp*

 foreach group in all boy girl below_baseline above_baseline  baselinesped baselinelep notspecial baselinefrpl notlunch   ///
	baselineblack baselinehisp   nonblackorhisp  {

g fpp_`group'= `v' if `group'==1
	local lab : variable label `group'

 global Y fpp_`group'
endog

qui eststo iv_${Y}: ivreg2 ${Y} (D = $Z1 $Z2) $covariates $risksets if  voter_sample==1 , partial($covariates  $risksets) robust
preserve
	qui regsave using sub_`v', ci pval addlabel(group, `group', label, `lab')  append
restore	
	}
	
}

*table versions
drop fpp_*
foreach group in all above_baseline below_baseline baselinesped baselinelep notspecial baselinefrpl notlunch   ///
	baselineblack baselinehisp baselinewhite baselineasian baselineotherrace  nonblackorhisp {
g vote_`group'= vote if `group'==1
g cog_`group'= cog if `group'==1
g noncog_`group'= noncog if `group'==1
g attend_`group'= attend if `group'==1
 g plans_`group'= plans_4yr if `group'==1

	
  global Y vote_`group'
	voterreg2 
 global Y cog_`group'
	voterreg2 
 global Y attend_`group'
	voterreg2 	
 global Y noncog_`group'
	voterreg2 
 global Y plans_`group'
	voterreg2 
	}


file open  t	using tn_index_sub.tex, replace write
	file write t	"\begin{sidewaystable}[htbp!] \centering" _n "\def\sym#1{\ifmmode^{#1}\else\(^{#1}\)\fi}" _n ///
					"\caption{The Impact of Charter School Attendance on Voting, Cognitive, and Non-Cognitive Indices, by Subgroups }" _n " \small \label{tn_index_sub}" _n ///
					"\begin{tabular*}{1\textwidth}{@{\extracolsep{\fill}}l*{11}{c}}" _n "\midrule" _n ///
					"&&		&		&  &					&Not &&Not && &White, \\" _n ///
					"&&Higher		&Lower		&Special  && Special&F/R& F/R && &Asian, and \\" _n ///
					"&All &Scores	&Scores	& Ed&EL&Needs &Lunch&Lunch&Black&Latinx & Other Race \\" _n ///
					"Index&(1)&(2)&(3)&(4)&(5)&(6)&(7)&(8)&(9)&(10)&(11)\\" _n ///
					"\midrule"  _n 
file close t

	esttab  iv_vote_all  iv_vote_above_baseline  iv_vote_below_baseline iv_vote_baselinesped iv_vote_baselinelep iv_vote_notspecial iv_vote_baselinefrpl iv_vote_notlunch iv_vote_baselineblack iv_vote_baselinehisp iv_vote_nonblackorhisp	///
		using tn_index_sub.tex, k($D) coef($D "Voting ") 		s(ccm , l( "\hspace{.25cm} CCM"  ""  ) f(3 ) lay( @ `""'  )) $opts  
	esttab  iv_cog_all iv_cog_above_baseline  iv_cog_below_baseline iv_cog_baselinesped iv_cog_baselinelep iv_cog_notspecial iv_cog_baselinefrpl iv_cog_notlunch	iv_cog_baselineblack iv_cog_baselinehisp iv_cog_nonblackorhisp ///
		 	using tn_index_sub.tex, k($D) coef($D "Cognitive ") 		s(ccm , l( "\hspace{.25cm} CCM"  ""  ) f(3 ) lay( @ `""'  )) $opts  
	esttab  iv_plans_all iv_plans_above_baseline  iv_plans_below_baseline iv_plans_baselinesped iv_plans_baselinelep iv_plans_notspecial iv_plans_baselinefrpl iv_plans_notlunch	iv_plans_baselineblack iv_plans_baselinehisp iv_plans_nonblackorhisp ///
		 	using tn_index_sub.tex, k($D) coef($D "Aspirations") 		s(ccm , l( "\hspace{.25cm} CCM"  ""  ) f(3 ) lay( @ `""'  )) $opts 	
	esttab  iv_attend_all iv_attend_above_baseline  iv_attend_below_baseline iv_attend_baselinesped iv_attend_baselinelep iv_attend_notspecial iv_attend_baselinefrpl iv_attend_notlunch	iv_attend_baselineblack iv_attend_baselinehisp iv_attend_nonblackorhisp ///
		 	using tn_index_sub.tex, k($D) coef($D "Noncognitive (Attendance)") 		s(ccm , l( "\hspace{.25cm} CCM"  ""  ) f(3 ) lay( @ `""'  )) $opts 
	esttab  iv_noncog_all iv_noncog_above_baseline  iv_noncog_below_baseline iv_noncog_baselinesped iv_noncog_baselinelep iv_noncog_notspecial iv_noncog_baselinefrpl iv_noncog_notlunch  iv_noncog_baselineblack iv_noncog_baselinehisp iv_noncog_nonblackorhisp	///
			using tn_index_sub.tex, k($D) coef($D "Noncognitive (Index)") s(ccm N, l( "\hspace{.25cm} CCM"  "" "\hspace{.25cm} \textit{N} " ) f(3 %9.0fc) lay( @ `""' @ )) $opts  
	
	file open  t 	using tn_index_sub.tex, append write
	file write t 	"\midrule" _n "\end{tabular*}" _n ///
					"\begin{tabular*}{1\textwidth}{p{8.4in}}" _n ///
					"\footnotesize Notes:  This table shows 2SLS estimates for subgroups of students from regressions limited to the sample listed in the header. Students categorized as ``not special needs'' are neither special education nor English learner students.  White, Asian, and other race students are combined into a single category due to small sample sizes in these groups. " ///
					"All other notes are the same as in Online Appendix Table \ref{tn_voter}. " ///
					"$note_stars" ///
					"\end{tabular*}" _n "\end{sidewaystable}" _n 
	file close t
	


 
use "$output/sub_vote.dta", clear
replace var = "vote"
append using "$output/sub_cog.dta"
replace var = "cog" if var=="D"
append using  "$output/sub_noncog.dta"
replace var = "noncog" if var=="D"
append using  "$output/sub_attend.dta"
replace var = "attend" if var=="D"
append using  "$output/sub_plans_4yr.dta"
replace var = "plans" if var=="D"

drop save r2  
g star  = ""
replace star = "*" if pval<0.1
replace star = "**" if pval<0.05
replace star = "***" if pval<0.05

reshape wide coef ci_* stderr pval N star, i(group label) j(var ) string



qui corr coefvote coefplans [aw=Nvote]
			local r = string( r(rho), "%9.3f")
			local n = r(N)
	local p = 2*ttail(`n'-2, abs(`r')*sqrt(`n'-2)/sqrt(1-`r'^2))
	di "`p'"
	if `p'<0.001{
			local s="***"
			}	
	else if `p'<0.05{
			local s="**"
			}	
	else if `p'<0.1{
			local s="*"
			}
	else if `p'>=0.1{
			local s=""
			}
		global d="{&rho}: `r'`s'"

g clock = 0
replace clock = 1 if group =="boy" |  group =="below_baseline" |  group =="all" |  group =="nonblackorhisp"|  group =="baselinesped"

twoway scatter  coefvote coefplans   [pweight = Nvote] , ms(Oh) msize(small) mc(gs10)  ///
	|| scatter  coefvote coefplans   [pweight = Nvote] if clock==0, ///
	ms(i) mlabel(label) mlabc(black) mlabg(1.2) mlabp(12) mlabs(vsmall)  /// 
	|| scatter  coefvote coefplans   [pweight = Nvote] if clock==1, ///
	ms(i) mlabel(label) mlabc(black) mlabg(1.2) mlabp(6) mlabs(vsmall)  ///
	|| lfit coefvote coefplans  [pweight = Nvote] , lw(medthick) lc(gs6) lp(solid)	///
	 text(.01 -.2 "${d}", size(small)) ///
	title("B. Aspirations  ")  ysc(range(0 .4))  yl(0(.1) .4) xsc(range(-.25 .3)) xl(-.25(.25).3) ///
	xtitle("Impact on Aspirations") ytitle("Impact on Voting", )  xsc(fextend) ysc(fextend) ///
	legend(off)  ///
	name(plans, replace)

qui corr coefvote coefattend [aw=Nvote]
			local r = string( r(rho), "%9.3f")
			local n = r(N)
	local p = 2*ttail(`n'-2, abs(`r')*sqrt(`n'-2)/sqrt(1-`r'^2))
	di "`p'"
	if `p'<0.001{
			local s="***"
			}	
	else if `p'<0.05{
			local s="**"
			}	
	else if `p'<0.1{
			local s="*"
			}
	else if `p'>=0.1{
			local s=""
			}
		global d="{&rho}: `r'`s'"

replace clock = 0
replace clock = 1 if group =="boy" |  group =="below_baseline" |  group =="all" |  group =="nonblackorhisp"|  group =="baselinesped"

twoway scatter  coefvote coefattend   [pweight = Nvote] , ms(Oh) msize(small) mc(gs10)  ///
	|| scatter  coefvote coefattend   [pweight = Nvote] if clock==0, ///
	ms(i) mlabel(label) mlabc(black) mlabg(1.2) mlabp(12) mlabs(vsmall)  /// 
	|| scatter  coefvote coefattend   [pweight = Nvote] if clock==1, ///
	ms(i) mlabel(label) mlabc(black) mlabg(1.2) mlabp(6) mlabs(vsmall)  ///
	|| lfit coefvote coefattend  [pweight = Nvote] , lw(medthick) lc(gs6) lp(solid)	///
	 text(.01 -.2 "${d}", size(small)) ///
	title("B. Noncognitive Skills  ")  ysc(range(0 .4))  yl(0(.1) .4) xsc(range(-.25 .3)) xl(-.25(.25).3) ///
	xtitle("Impact on Noncognitive Skills (Attendance)") ytitle("Impact on Voting", )  xsc(fextend) ysc(fextend) ///
	legend(off)  ///
	name(attend, replace)
	
twoway scatter  coefvote coefattend   [pweight = Nvote] , ms(Oh) msize(small) mc(gs10)  ///
	|| scatter  coefvote coefattend   [pweight = Nvote] if clock==0, ///
	ms(i) mlabel(label) mlabc(black) mlabg(1.2) mlabp(12) mlabs(vsmall)  /// 
	|| scatter  coefvote coefattend   [pweight = Nvote] if clock==1, ///
	ms(i) mlabel(label) mlabc(black) mlabg(1.2) mlabp(6) mlabs(vsmall)  ///
	|| lfit coefvote coefattend  [pweight = Nvote] , lw(medthick) lc(gs6) lp(solid)	///
	 text(.01 -.2 "${d}", size(small)) ///
	title("D. Noncognitive Skills  ")  ysc(range(0 .4))  yl(0(.1) .4) xsc(range(-.25 .3)) xl(-.25(.25).3) ///
	xtitle("Impact on Noncognitive Skills (Attendance)") ytitle("Impact on Voting", )  xsc(fextend) ysc(fextend) ///
	legend(off)  ///
	name(attendD, replace)

qui corr coefvote coefnoncog [aw=Nvote]
			local r = string( r(rho), "%9.3f")
			local n = r(N)
	local p = 2*ttail(`n'-2, abs(`r')*sqrt(`n'-2)/sqrt(1-`r'^2))
	di "`p'"
	if `p'<0.001{
			local s="***"
			}	
	else if `p'<0.05{
			local s="**"
			}	
	else if `p'<0.1{
			local s="*"
			}
	else if `p'>=0.1{
			local s=""
			}
		global d="{&rho}: `r'`s'"

replace clock=0
replace clock = 1 if group =="boy" |  group =="below_baseline" |  group =="all" |  group =="nonblackorhisp"|  group =="notspecial"

twoway scatter  coefvote coefnoncog   [pweight = Nvote] , ms(Oh) msize(small) mc(gs10)  ///
	|| scatter  coefvote coefnoncog   [pweight = Nvote] if clock==0, ///
	ms(i) mlabel(label) mlabc(black) mlabg(1) mlabp(1) mlabs(vsmall)  /// 
	|| scatter  coefvote coefnoncog   [pweight = Nvote] if clock==1, ///
	ms(i) mlabel(label) mlabc(black) mlabg(1) mlabp(4) mlabs(vsmall)  ///
	|| lfit coefvote coefnoncog  [pweight = Nvote] , lw(medthick) lc(gs6) lp(solid)	///
	 text(.01 -.45 "${d}", size(small)) ///
	title("B. Non-Cognitive Skills  ")  ysc(range(0 .4))  yl(0(.1) .4) xsc(range(-.5 .25)) xl(-.5(.25).25) ///
	xtitle("Impact on Non-Cognitive Skills (Index)") ytitle("Impact on Voting", )  xsc(fextend) ysc(fextend) ///
	legend(off)  ///
	name(noncog, replace)
			
replace clock = 0
replace clock = 1 if group =="baselinesped" |  group =="girl" |  group =="all" 
replace clock = 2 if   group =="notspecial"
	
qui corr coefvote coefcog [aw=Nvote]
			local r = string( r(rho), "%9.3f")
			local n = r(N)
	local p = 2*ttail(`n'-2, abs(`r')*sqrt(`n'-2)/sqrt(1-`r'^2))
	di "`p'"
	if `p'<0.001{
			local s="***"
			}	
	else if `p'<0.05{
			local s="**"
			}	
	else if `p'<0.1{
			local s="*"
			}
	else if `p'>=0.1{
			local s=""
			}
		global d="{&rho}: `r'`s'"
		
twoway scatter  coefvote coefcog   [pweight = Nvote] , ms(Oh) msize(small) mc(gs5)  ///
	|| scatter  coefvote coefcog   [pweight = Nvote] if clock==0, ///
	ms(i) mlabel(label) mlabc(black) mlabg(1) mlabp(1) mlabs(vsmall)  /// 
	|| scatter  coefvote coefcog   [pweight = Nvote] if clock==1, ///
	ms(i) mlabel(label) mlabc(black) mlabg(1) mlabp(4) mlabs(vsmall)  ///
	|| scatter  coefvote coefcog   [pweight = Nvote] if clock==2, ///
	ms(i) mlabel(label) mlabc(black) mlabg(1) mlabp(11) mlabs(vsmall)  ///
	|| lfit coefvote coefcog  [pweight = Nvote] , lw(medthick) lc(gs6) lp(solid)	///
		 text(.01 .37 "${d}", size(small)) ///
title("A. Cognitive Skills  ")  ysc(range(0 .4))  yl(0(.1) .4) xsc(range(.35 .7)) xl(.4(.1).7) ///
	xtitle("Impact on Cognitive Skills") ytitle("Impact on Voting", )  xsc(fextend) ysc(fextend) ///
	legend(off)  ///
	name(cog, replace)
	
twoway scatter  coefvote coefcog   [pweight = Nvote] , ms(Oh) msize(small) mc(gs5)  ///
	|| scatter  coefvote coefcog   [pweight = Nvote] if clock==0, ///
	ms(i) mlabel(label) mlabc(black) mlabg(1) mlabp(1) mlabs(vsmall)  /// 
	|| scatter  coefvote coefcog   [pweight = Nvote] if clock==1, ///
	ms(i) mlabel(label) mlabc(black) mlabg(1) mlabp(4) mlabs(vsmall)  ///
	|| scatter  coefvote coefcog   [pweight = Nvote] if clock==2, ///
	ms(i) mlabel(label) mlabc(black) mlabg(1) mlabp(11) mlabs(vsmall)  ///
	|| lfit coefvote coefcog  [pweight = Nvote] , lw(medthick) lc(gs6) lp(solid)	///
		 text(.01 .37 "${d}", size(small)) ///
title("C. Cognitive Skills  ")  ysc(range(0 .4))  yl(0(.1) .4) xsc(range(.35 .7)) xl(.4(.1).7) ///
	xtitle("Impact on Cognitive Skills") ytitle("Impact on Voting", )  xsc(fextend) ysc(fextend) ///
	legend(off)  ///
	name(cogC, replace)
	
	
	graph combine cog noncog, col(1) xsize(8.5) ysize(11)
	graph export f_cog_noncog.pdf, replace
	
	graph combine cog attend, col(1) xsize(8.5) ysize(11)
	graph export f_cog_noncog_attend.pdf, replace

			graph combine sub_share_pres sub_first_pos_pres ///
				cogC attendD, col(2) xsize(8.5) ysize(8.5) iscale(.5)
	graph export f_sub_combined.pdf, replace



	}
if $tn_ltospec == 1{

voteruse


*CCMs for AP
cap drop oneminusD
g oneminusD = 1 - $D

qui g took_any_Y0=took_any*oneminusD

 ivreg2 took_any_Y0 (oneminusD = $Z1 $Z2) $covariates  $risksets if  voter_sample==1, partial($covariates  $risksets) robust
 
 *CCM all cohorts: .2825841  ( .0211342 )
		
 ivreg2 took_any_Y0 (oneminusD = $Z1 $Z2) $covariates  $risksets if  voter_sample==1&proj<=2012, partial($covariates  $risksets) robust

 *CCM 2012 and prior cohorts:    .237445   (.0352894  )
 
 ivreg2 took_any_Y0 (oneminusD = $Z1 $Z2) $covariates  $risksets if  voter_sample==1&proj>2012, partial($covariates  $risksets) robust

 *CCM 2012 and prior cohorts:    .3090192   (.0261954 )
 
 
local robustvars  c_state_mrawsc10   took_any  above_s3_any  took_sat score_satreason     att_4yr_byY2fall att_2yr_byY2fall first_pos_pres
estimates clear

foreach y of varlist `robustvars'  {
global Y `y'
	endog
	qui eststo iv_${Y}: ivreg2 ${Y} ($D = $Z1 $Z2) $covariates $risksets if  voter_sample==1 ///
			, partial($covariates  $risksets) robust /*cluster($clustervar)*/ 
			
}

	file open  t	using tn_ltospec.tex, replace write
	file write t	"\begin{sidewaystable}[htbp!] \centering" _n "\def\sym#1{\ifmmode^{#1}\else\(^{#1}\)\fi}" _n ///
					"\caption{Alternative Specifications: Comparison to Angrist et al. (2016)}" _n "\label{tn_ltospec} \small" _n ///
					"\begin{tabular*}{1\textwidth}{@{\extracolsep{\fill}}l*{8}{c}}" _n "\midrule" _n ///
					"&	10th	&Took &			&		&SAT	&	Enroll &Enroll &Voted in 1st\\" _n ///
					"& Grade 	& Any&Above 3	& Took&Score&		4-Year&2-Year & Possible\\" _n ///
					"&Math & AP & Any AP	 &SAT & (1600)&College&College& Presidential \\" _n ///
					"&(1)&(2)&(3)&(4)&(5)&(6)&(7)&(8)\\" _n ///
					"\midrule"  _n 
file close t

	esttab iv_* 	using tn_ltospec.tex, k($D) coef($D "Main specification ") 		  $opts  
	local n1 = e(N)
	
estimates clear
global Z1 initial_offer_LTO
global Z2 waitlist_offer_LTO
	g D2 = D_LTO

foreach y of varlist `robustvars'  {
global Y `y'
	replace D2 = D_by12
	if "${Y}" == "c_state_mrawsc10"{
		replace D2 = D_by10
	}
	qui eststo iv_${Y}: ivreg2 ${Y} (D2 = $Z1 $Z2)  $covariates dl_* if  lto_sample==1 ///
			, partial( $covariates dl_* ) robust cluster($clustervar)
}
	esttab iv_* 	using tn_ltospec.tex, k(D2) coef(D2 "+ Omitting new schools") 		 $opts  
	local n2 = e(N)
	
	*college vars should be restrice to class of 2011 and early
	foreach v of varlist att_4yr_byY2fall att_2yr_byY2fall{
		replace `v'=. if proj_year12>2011
	}
	
estimates clear
foreach y of varlist `robustvars'  {
global Y `y'
	replace D2 = D_by12
	if "${Y}" == "c_state_mrawsc10"{
		replace D2 = D_by10
	}
	qui eststo iv_${Y}: ivreg2 ${Y} (D2 = $Z1 $Z2)  $covariates dl_*  if  lto_sample==1&proj<=2012 ///
			, partial($covariates  dl_* ) robust cluster($clustervar)
}
	esttab iv_* 	using tn_ltospec.tex, k(D2) coef(D2 "+ Omitting new cohorts") 		 $opts  
	local n3 = e(N)
	
	
	
estimates clear
foreach y of varlist `robustvars'  {
global Y `y'
	replace D2 =  D_by12
	if "${Y}" == "c_state_mrawsc10"{
		replace D2 = D_by10
	}
	qui eststo iv_${Y}: ivreg2 ${Y} (D2= $Z1 $Z2) baselinefemale baselineblack baselinehisp baselineasian baselineotherrace  ///
		baselinesped baselinelep baselinefrpl   yobdum* yearLTOdum*  dl_* if  lto_sample==1&proj<=2012 ///
			, partial(baselinefemale baselineblack baselinehisp baselineasian baselineotherrace ///
		baselinesped baselinelep baselinefrpl   yobdum* yearLTOdum*  dl_*) robust cluster($clustervar)
}
	esttab iv_* 	using tn_ltospec.tex, k(D2) coef(D2 "+ Adding 10th grade year dummies") 		 $opts  
	local n4 = e(N)

estimates clear
foreach y of varlist `robustvars'  {
global Y `y'

	qui eststo iv_${Y}: ivreg2 ${Y} (D_LTO   = $Z1 $Z2) baselinefemale baselineblack baselinehisp baselineasian baselineotherrace i.baselinefemale#i.baselineblack i.baselinefemale#i.baselinehisp ///
		baselinesped baselinelep baselinefrpl   yobdum* yearLTOdum*  dl_* if    lto_sample==1&proj<=2012 ///
			, partial(baselinefemale baselineblack baselinehisp baselineasian baselineotherrace ///
		baselinesped baselinelep baselinefrpl   yobdum* yearLTOdum* i.baselinefemale#i.baselineblack i.baselinefemale#i.baselinehisp   dl_*) robust cluster($clustervar)
}
	esttab iv_* 	using tn_ltospec.tex, k(D_LTO) coef(D_LTO "+ Changing endogenous variable") 		 $opts  
	local n5 = e(N)
	


	file open  t 	using tn_ltospec.tex, append write
	file write t 			///
		"Angrist, et al. (2016)&0.489*** & 0.298*** & 0.122* &0.084 & 78.1**&0.183*&-0.108+& -- \\" _n ///
					"&(0.146)&(0.062)&(0.051)			&(0.063)&(23.9)&(0.073)&(0.61)&\\" _n ///
					"\midrule" _n "\end{tabular*}" _n ///
					"\begin{tabular*}{1\textwidth}{p{8.4in}}" _n ///
					"\footnotesize Notes:  " ///
					"The first row of the table repeats the main specification reported in the other tables, see Tables \ref{tn_academic} and \ref{tn_voter} for details (N = `n1'). " ///
					"Each subsequent row shows an alternative specification. " /// 
					"The row labeled \`\`+ Omitting new schools'' excludes charter schools added to the sample in addition to the schools in Angrist et al. (2016)  (N = `n2'). " ///
					"The row labeled \`\`+ Omitting new cohorts'' excludes projected high school classes added to the sample in addition to the classes in Angrist et al. (2016) in addition to the above change  (N = `n3'). " ///
					"The row labeled \`\`Adding 10th grade year dummies'' adds a year fixed effect based on 10th grade year, which conditions on presence in the data in 10th grade, as in Angrist et al. (2016), in addition to the above changes  (N = `n4'). " ///
					"The row labeled \`\`Changing endogenous variable'' switches the endogenous variables to one that only counts charter attendance in 9th or 10th grade, as in Angrist et al. (2016), in addition to the above changes  (N = `n5'). " ///
					"The final row reprints the corresponding estimates from Angrist et al. (2016) (N = 3,205). " ///
					"Sample sizes are from the voting outcomes and differ for other outcomes. " ///
					"$note_stars" ///
					"\end{tabular*}" _n "\end{sidewaystable}" _n 
	file close t
	
	global Z1 initial_offer
global Z2 waitlist_offer
	
}	
if $fn_robust == 1{
estimates clear


local letter_list "A B C D E F G H I J K L"
local list_num=1

local robustvars  ev fpp
voteruse
g all = 1
ren share_pres ev
ren first_pos_pres fpp

egen totapp = rowtotal( applyRoxPrep   applyBGA   applyCoaHII applyMATCH_HS applyEdBrooke applyBosPrep  applyExcel  applyBosCol applyMATCH_MS applyCoaH  applyAPR applyCodman )


foreach g in all {
preserve	
keep if `g'==1
foreach y of varlist `robustvars'  {
global Y `y'
endog
	qui ivreg2 ${Y} ($D = $Z1 $Z2) $covariates $risksets if  voter_sample==1 , partial($covariates $risksets ) robust 
	global Y_`y'_`g' = _b[${D}]
foreach t of numlist 2006/2017 {
	label var $D `t'
	qui  ivreg2 ${Y} ($D = $Z1 $Z2) $covariates $risksets  if  voter_sample==1 &proj_year12!=`t', partial($covariates $risksets ) robust
	 eststo `y'`t'`g'
}	


foreach v of varlist  applyRoxPrep   applyBGA   applyCoaHII applyMATCH_HS applyEdBrooke applyBosPrep  applyExcel  applyBosCol applyMATCH_MS applyCoaH  applyAPR applyCodman {
	
	cap drop *only
	g `v'_only = `v' if totapp==1
	replace `v'_only = 0 if `v'_only ==.
local letter: word `list_num' of  `letter_list'

	label var $D `letter'
	qui ivreg2 ${Y} ($D = $Z1 $Z2) $covariates $risksets if  voter_sample==1 &`v'_only!=1, partial($covariates $risksets ) robust
	 eststo `y'`letter'`g'
	 local ++list_num
}
local list_num =1

}
restore
}


coefplot (ev2006all, label("Share Presidential" )) (fpp2006all, label("Voted in First Possible Presidential Election" )) || ///
	ev2007all fpp2007all || ev2008all fpp2008all  || ev2009all fpp2009all || ///
	ev2010all fpp2010all || ev2011all fpp2011all || ev2012all fpp2012all || ev2013all fpp2013all || ///
	ev2014all fpp2014all || ev2015all fpp2015all || ev2016all fpp2016all || ev2017all fpp2017all ///
 ,  vertical	 yline(0)  bycoefs    ///
  bylabels("2006" "2007" "2008" "2009" "2010" "2011" "2012" "2013" "2014" "2015" "2016" "2017") ///
	yline(${Y_ev_all}, lw(thin) lcolor(black) ) ///
	yline(${Y_fpp_all}, lw(thin) lcolor(gray) ) ///
	 msymbol(O)  legend(pos(6) row(1) ) ///
	 title("A. Dropping Cohorts") ///
	 ysc(range(-0.1 0.2)) ylabel(-0.1 (0.1) 0.2) yt(-0.1 (0.1) 0.2) ///
	 xsc(fextend)  ysc(fextend) ///
	xtitle("Omitting Projected High School Class of...")  name(omit_year_all, replace)
	

	
coefplot (evAall, label("Share Presidential" )) (fppAall, label("Voted in First Possible Presidential Election" )) || ///
	evBall fppBall|| evCall fppCall  || evDall fppDall || ///
	evEall fppEall || evFall fppFall || evGall fppGall || evHall fppHall || ///
	evIall fppIall || evJall fppJall || evKall fppKall  ///
 , xsc(fextend)  ysc(fextend) vertical	  yline(0)  bycoefs    ///
  bylabels("A" "B" "C" "D" "E" "F" "G" "H" "I" "J" "K" ) ///
	yline(${Y_ev_all}, lw(thin) lcolor(black) ) ///
	yline(${Y_fpp_all}, lw(thin) lcolor(gray) ) ///
	 msymbol(O)  legend(pos(6) row(1) ) ///
	 ysc(range(-0.1 0.2)) ylabel(-0.1 (0.1) 0.2) yt(-0.1 (0.1) 0.2) ///
	 title("B. Dropping Schools") ///
	xtitle("Omitting School...")   name(omit_school_all, replace)
	

grc1leg omit_year_all  omit_school_all   , col(1) name(omit, replace) ycommon

graph display omit , xsize(8.5) ysize(11) 
	graph save "$output\f_omit.gph", replace
	graph export f_omit.pdf, replace
	
}
if $tn_robust == 1{

estimates clear

local robustvars    ever_registered   share_pres  first_pos_pres 

voteruse

	preserve

foreach y of varlist `robustvars'  {
global Y `y'
	endog
	qui eststo iv_${Y}: ivreg2 ${Y} ($D = $Z1 $Z2) $covariates $risksets if  voter_sample==1 ///
			, partial($covariates  $risksets ) robust 
}

	file open  t	using tn_robust.tex, replace write
	file write t	"\begin{table}[htbp!] \centering" _n "\def\sym#1{\ifmmode^{#1}\else\(^{#1}\)\fi}" _n ///
					"\caption{Alternative Specifications}" _n "\label{tn_robust}" _n  "\small" _n ///
					"\begin{tabular*}{1\textwidth}{@{\extracolsep{\fill}}l*{3}{c}}" _n "\midrule" _n ///
					"&Ever& Share&First Possible \\" _n ///
					" & Registered&Presidential & Presidential  \\" _n ///
					"&(1)&(2)&(3)\\" _n ///
					"\midrule"  _n 
file close t

	esttab iv_* 	using tn_robust.tex, k($D) coef($D "Main specification ") 		  $opts  
	estimates restore iv_ever_registered
	local n1 = e(N)
	

drop if turn18<=td(4nov2008) // those who became 18 right before 2008
estimates clear
foreach y of varlist `robustvars'   {
global Y `y'
	endog
	qui eststo iv_${Y}: ivreg2 ${Y} ($D = $Z1 $Z2) $covariates $risksets if  voter_sample==1 ///
			, partial($covariates $risksets ) robust 
}
	esttab iv_* 	using tn_robust.tex, k($D) coef($D "Excluding 2008 cohorts") 		 $opts  
	estimates restore iv_ever_registered
	local n2 = e(N)

restore 
preserve

drop if turn18>td(4nov2008)&turn18<=td(6nov2012) // those who became 18 right before 2012
estimates clear
foreach y of varlist `robustvars'   {
global Y `y'
	endog
	qui eststo iv_${Y}: ivreg2 ${Y} ($D = $Z1 $Z2) $covariates $risksets if  voter_sample==1 ///
			, partial($covariates $risksets ) robust 
}
	esttab iv_* 	using tn_robust.tex, k($D) coef($D "Excluding 2012 cohorts") 		 $opts  
	estimates restore iv_ever_registered
	local n3 = e(N)

restore 
preserve 

drop if turn18>td(6nov2012) // those who became 18 right before 2016
estimates clear
foreach y of varlist `robustvars'   {
global Y `y'
	endog
	qui eststo iv_${Y}: ivreg2 ${Y} ($D = $Z1 $Z2) $covariates $risksets  if  voter_sample==1 ///
			, partial($covariates $risksets ) robust 
}
	esttab iv_* 	using tn_robust.tex, k($D) coef($D "Excluding 2016 cohorts") 		 $opts  
	estimates restore iv_ever_registered
	local n4 = e(N)

restore 

estimates clear
foreach y of varlist `robustvars'   {
global Y `y'
	endog
	qui eststo iv_${Y}: ivreg2 ${Y} ($D = $Z1 $Z2)  $risksets if  voter_sample==1 ///
			, partial( $risksets) robust 	
}
	esttab iv_* 	using tn_robust.tex, k($D) coef($D "No covariates") 		  $opts  
	estimates restore iv_ever_registered
	local n5 = e(N)

estimates clear
foreach y of varlist `robustvars'  {
global Y `y'
	endog
	qui eststo iv_${Y}: ivreg2 ${Y} ($D = $Z1 $Z2)  $covariates baseline_m baseline_e $risksets if  voter_sample==1 ///
			, partial($covariates $risksets ) robust 
}
	esttab iv_* 	using tn_robust.tex, k($D) coef($D "Add baseline tests") 		  $opts  
	estimates restore iv_ever_registered
	local n6 = e(N)

	estimates clear
foreach y of varlist `robustvars'   {
global Y `y'
	
	qui eststo iv_${Y}: ivreg2 ${Y} (D_within2 = $Z1 $Z2) $covariates $risksets  if  voter_sample==1 ///
			, partial($covariates $risksets ) robust /*cluster($clustervar)*/	
}
	esttab iv_* 	using tn_robust.tex, k(D_within2) coef(D_within2 "Alternative endogenous")  $opts  
	estimates restore iv_ever_registered
	local n7 = e(N)

estimates clear
foreach y of varlist `robustvars'   {
global Y `y'
	
	qui eststo iv_${Y}: ivreg2 ${Y} ($D = $Z1 ) $covariates $risksets  if  voter_sample==1 ///
			, partial($covariates $risksets ) robust
}
	esttab iv_* 	using tn_robust.tex, k($D) coef($D "Initial offer only") $opts  
	estimates restore iv_ever_registered
	local n8 = e(N)
	
estimates clear
foreach y of varlist `robustvars'   {
global Y `y'
	
	qui eststo iv_${Y}: ivreg2 ${Y} ($D = $Z1 $Z2 ) $covariates $risksets  if  voter_sample==1 ///
			, partial($covariates $risksets ) robust cluster($clustervar)
}
	esttab iv_* 	using tn_robust.tex, k($D) coef($D "Cluster S.E.'s") $opts  
	estimates restore iv_ever_registered
	local n9 = e(N)

	file open  t 	using tn_robust.tex, append write
	file write t 		"\midrule" _n "\end{tabular*}" _n ///
					"\begin{tabular*}{1\textwidth}{p{6.3in}}" _n ///
					"\footnotesize Notes:  " ///
					"The first row of the table repeats the main specification reported in the other tables, see Table \ref{tn_voter} for details (N = `n1'). " ///
					"Each subsequent row shows an alternative specification. " /// 
					"The row labeled \`\`Excluding 2008 cohorts'' excludes students whose first opportunity to vote in a presidential election was on November 4th, 2008  (N = `n2'). " ///
					"The row labeled \`\`Excluding 2012 cohorts'' excludes students whose first opportunity to vote in a presidential election was on November 6th, 2012 (N = `n3'). " ///
					"The row labeled \`\`Excluding 2016 cohorts'' excludes students whose first opportunity to vote in a presidential election was on November 8th, 2016  (N = `n4'). " ///
					"The row labeled \`\`No covariates'' removes baseline demographic characteristics from the main specification  (N = `n5'). " ///
					"The row labeled \`\`Add baseline tests'' adds baseline test scores to the main specification, which also restricts the sample to those students with reported baseline test scores  (N = `n6'). " ///
					"The row labeled \`\`Alternative endogenous'' uses charter attendance in the first two years after the lottery as the endogenous variable rather than any attendance before the outcome  (N = `n7'). " ///
					"The row labeled \`\`Initial offer only'' uses the  offer on the day of charter school lottery as the only instrument (N = `n8'). " ///
							"The row labeled \`\`Cluster S.E.'s'' clusters the standard errors by school of attendance after the lottery and year (N = `n9'). " ///
		 "$note_stars" ///
					"\end{tabular*}" _n "\end{table}" _n 
	file close t

}	
if $tn_students_voterfile==1{

*added by Cam Arnzen Aug 6 2021 
estimates clear
voteruse
keep if voter_sample==1

foreach x of varlist ever_MA ever_CT ever_ME ever_NH ever_NY ever_PA  ever_RI ever_VT {
	replace `x' = 0 if `x' == .
}

tostring college_state, gen(college_state_str)
*g college_MA == 0
replace college_MA = 0 if college_MA == .
label var college_MA "Massachusetts"

gen college_CT = 1 if college_state_str == "9"
replace college_CT = 0 if college_CT == .
label var college_CT "Connecticut"

gen college_ME = 1 if college_state_str == "23"
replace college_ME = 0 if college_ME == .
label var college_ME "Maine"

gen college_NH = 1 if college_state_str == "33"
replace college_NH = 0 if college_NH == .
label var college_NH "New Hampshire"

gen college_NY = 1 if college_state_str == "36"
replace college_NY = 0 if college_NY == .
label var college_NY "New York"

gen college_PA = 1 if college_state_str == "42"
replace college_PA = 0 if college_PA == . 
label var college_PA "Pennsylvania"

gen college_RI = 1 if college_state_str == "44"
replace college_RI = 0 if college_RI == . 
label var college_RI "Rhode Island"

gen college_VT = 1 if college_state_str == "50"
replace college_VT = 0 if college_VT == .
label var college_VT "Vermont"

gen college_Other = 1 if college_state_str != "." & college_state_str != "25" & college_state_str != "9" & college_state_str != "23" & college_state_str != "33" & college_state_str != "36"  & college_state_str != "42"& college_state_str != "44" & college_state_str != "50" 
replace college_Other = 0 if college_Other == .
label var college_Other "Other States"

gen college_NoCollege = 1 if college_state_str == "."
replace college_NoCollege = 0 if college_NoCollege == . 
label var college_NoCollege "No College"

gen college_all = 1 if voter_sample == 1
label var college_all "All"

*Table Start & Formatting
	file open  t	using tn_votertab.tex, replace write
	file write t	"\begin{sidewaystable}[htbp!] \centering" _n "\def\sym#1{\ifmmode^{#1}\else\(^{#1}\)\fi}" _n ///
					"\caption{Presence in State Voter Files}" _n "\label{tn_votertab}" _n "\small" _n ///
					"\begin{tabular*}{1\textwidth}{@{\extracolsep{\fill}}l*{9}{c}}" _n "\midrule" _n ///
					"\hspace{.5cm} College State & \textit{N}&MA        &CT &ME &NH &NY&PA&RI  &VT\\\\" _n ///
					"\midrule" _n		///
					"(A) Charter applicants  &${N_voter}  &\\" _n "\cmidrule{1-1}" _n 
file close  t	

*Voter Panel - 9562 Obs
foreach y of varlist college_MA college_CT college_ME college_NH college_NY college_PA college_RI college_VT college_Other college_NoCollege college_all { 
	foreach g in ever_MA ever_CT ever_ME ever_NH ever_NY ever_PA ever_RI ever_VT{
*		use "`voter'", clear
		global Y `y'
		global lab_${Y} : variable label ${Y}
		qui su `g' if `y'==1
		global m_`g'=string(r(mean), "%9.3f")
	}
	
	qui count if `y' ==1
	global N_`y'=string(r(N), "%9.0fc")
	
file open  t	using tn_votertab.tex, append write	
file write t  	"\hspace{.5cm} ${lab_`y'} &${N_`y'} &${m_ever_MA}& ${m_ever_CT}& ${m_ever_ME}& ${m_ever_NH}& ${m_ever_NY}& ${m_ever_PA}& ${m_ever_RI}& ${m_ever_VT} \\" _n 
file close  t			
}

*** Massachusetts Panel - 789,592 Obs
use  "$data\descriptivesfile_ma9th.dta", clear
keep if atleast18==1

file open  t 	using tn_votertab.tex, append write
file write t	"& & & & & & & & \\" _n "\cmidrule{1-1}" _n "(B) Massachusetts  &${N_maps} &\\" _n "\cmidrule{1-1}" _n
file close  t		

foreach x of varlist ever_MA ever_CT ever_ME ever_NH ever_NY ever_PA ever_RI ever_VT{
	replace `x' = 0 if `x' == .
}

tostring college_state, gen(college_state_str)
*g college_MA == 0
replace college_MA = 0 if college_MA == .
label var college_MA "Massachusetts"

gen college_CT = 1 if college_state_str == "9"
replace college_CT = 0 if college_CT == .
label var college_CT "Connecticut"

gen college_ME = 1 if college_state_str == "23"
replace college_ME = 0 if college_ME == .
label var college_ME "Maine"

gen college_NH = 1 if college_state_str == "33"
replace college_NH = 0 if college_NH == .
label var college_NH "New Hampshire"

gen college_NY = 1 if college_state_str == "36"
replace college_NY = 0 if college_NY == .
label var college_NY "New York"

gen college_PA = 1 if college_state_str == "42"
replace college_PA = 0 if college_PA == . 
label var college_PA "Pennsylvania"

gen college_RI = 1 if college_state_str == "44"
replace college_RI = 0 if college_RI == . 
label var college_RI "Rhode Island"

gen college_VT = 1 if college_state_str == "50"
replace college_VT = 0 if college_VT == .
label var college_VT "Vermont"

gen college_Other = 1 if college_state_str != "." & college_state_str != "25" & college_state_str != "9" & college_state_str != "23" & college_state_str != "33" & college_state_str != "36"  & college_state_str != "42" & college_state_str != "44" & college_state_str != "50" 
replace college_Other = 0 if college_Other == .
label var college_Other "Other States"

gen college_NoCollege = 1 if college_state_str == "."
replace college_NoCollege = 0 if college_NoCollege == . 
label var college_NoCollege "No College"

gen college_all = 1 if atleast18 == 1
label var college_all "All"

foreach y of varlist college_MA college_CT college_ME college_NH college_NY college_PA college_RI college_VT college_Other college_NoCollege college_all { 
	foreach g in ever_MA ever_CT ever_ME ever_NH ever_NY ever_PA ever_RI ever_VT{
		global Y `y'
		global lab_${Y} : variable label ${Y}
		qui su `g' if `y'==1
		global m_`g'=string(r(mean), "%9.3f")
	}
	qui count if `y' ==1
	global N_`y'=string(r(N), "%9.0fc")
	
file open  t	using tn_votertab.tex, append write	
file write t  	"\hspace{.5cm} ${lab_`y'} &${N_`y'} &${m_ever_MA}& ${m_ever_CT}& ${m_ever_ME}& ${m_ever_NH}& ${m_ever_NY}&  ${m_ever_PA}&${m_ever_RI}& ${m_ever_VT} \\" _n 
file close  t			
}

	file open  t 	using tn_votertab.tex, append write
	file write t 	"& & & & & & & & \\"  _n  ///	
					"\midrule" _n "\end{tabular*}" _n ///
					"\begin{tabular*}{1\textwidth}{p{8.4in}}" _n ///
			"\footnotesize Notes:  " ///
					"This table shows the rates in which students appear in voter files for Massachusetts and nearby states, by state of college attended. " ///
					"The charter applicants are restricted to students who applied for a Boston charter school lottery. " ///
					"The Massachusetts panel shows all 9th grade students in Massachusetts.  " ///
					"\end{tabular*}" _n "\end{sidewaystable}" _n 
	file close t

}
